admin管理员组

文章数量:1410697

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/;

本文标签: javascriptUncaught SyntaxError Invalid flags supplied to RegExp constructor 39b39Stack Overflow