Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  28] [ 4]  / answers: 1 / hits: 16863  / 11 Years ago, wed, september 18, 2013, 12:00:00

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.


More From » javascript

 Answers
23

Use capture groups?



.*?b(S)


Regular



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



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|()

[#75616] Tuesday, September 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;