Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  161] [ 4]  / answers: 1 / hits: 16462  / 9 Years ago, wed, may 20, 2015, 12:00:00

I am attempting to search a string for a specific word ('cow') using the following:



var regex = new RegExp('cow', '\b');


I only wish to target 'cow' and not words which contain 'cow' such as 'cowboy' or 'cows' using the 'b' expression, however this results in:




Uncaught SyntaxError: Invalid flags supplied to RegExp constructor
'b'




I have attempted to use 'b', 'b', '/b' but all result in the same error.



What is the correct expression I need to use?


More From » regex

 Answers
9

You're confusing the regular expression special characters with the flags, it should be:



var regex = new RegExp('\bcow\b', 'g');


The g is the global flag, to search the supplied string for all matches.



References:




[#66520] Tuesday, May 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;