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?
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?
Share Improve this question asked May 20, 2015 at 21:03 user1444027user1444027 5,2619 gold badges30 silver badges40 bronze badges2 Answers
Reset to default 2You'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:
RegExp
.
2nd parameter for RegExp
object is flag like g
or i
etc. Just use
var regex = new RegExp('\\bcow\\b');
or simply use regex delimiter:
var regex = /\bcow\b/;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744318604a4568302.html
评论列表(0条)