javascript - Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'b' - Stack Overflow

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

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 badges
Add a ment  | 

2 Answers 2

Reset to default 2

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:

  • 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信