Nash3man
Nash3man

Reputation: 175

Whole word search in javascript using regex

I'm trying to perform a whole word search in javascript using the following regex.

str = "Test String C.S (example)";
var regex_search = new RegExp("\\b"+search_string+"\\b","g");
if(str.match(regex_search)) != null)
  match = true;
else
  match = false;

The above works well if I search for a normal string like 'String'. But if I search for just 'S', it returns C.S as a match. Also, searching for example returns a match but in this case I do not want a match because it has parenthesis. I just want to match the whole word only. Any suggestions would be greatly appreciated.

--Edit--

Thanks to @plalx Clarified the example.

Upvotes: 3

Views: 17450

Answers (2)

plalx
plalx

Reputation: 43718

Word boundaries are all non-word characters, which includes the . character. You will have to use something else than \b.

I am sure the regex can be simplified, but you could use something like:

function containsWord(string, word) {
    return new RegExp('(?:[^.\w]|^|^\\W+)' + word + '(?:[^.\w]|\\W(?=\\W+|$)|$)').test(string);
}

containsWord('test', 'test'); //true
containsWord('.test', 'test'); //true
containsWord('test.something', 'test'); //false
containsWord('test. something', 'test'); //true
containsWord('test.   something', 'test'); //true
containsWord('S.C', 'S'); //false
containsWord('S.C', 'S.C'); //true

Upvotes: 4

progrenhard
progrenhard

Reputation: 2363

Use capture groups?

.*?\b(S)

Regular expression visualization

Debuggex Demo

I think your second \b is breaking your code also.

Just replace the (S) with value you want to find.

Not really sure exactly what you're asking to be honest. Or what you are trying to find.

edit:

.*?(?:^|\s)(S[^\s$]*).*?

Regular expression visualization

Debuggex Demo

you can prob take out the .*? at the start and the end of the regex put it in there for thoroughness.

replace the S in front of [^\s$] with the value you want to check. Also, if you want to allow more things in front of the value all you have to do is add an extra |"character" in the first capture group.

for example a parenthesis

.*?(?:^|\s|\()

Upvotes: 6

Related Questions