Word boundary won't match start or end in javascript

I get unexpected results with this code:

'foo'.match(new RegExp('\bfoo\b')); // Returns null 

Why does this return null while this returns "foo"?

 'foo'.match(new RegExp('foo')); // Returns "foo" 

Does the word boundary marker match the start and end?

EDIT: I need the regex to be a string because I am inserting variables into it.

+6
javascript regex word-boundary
source share
3 answers

Backslash Escape

 'foo'.match(new RegExp('\\bfoo\\b')); 
+13
source share
 "foo".match(/\bfoo\b/); 

gotta do it for you

0
source share

Do not insert it in quotation marks ... instead, do the following: -

 'foo'.match(new RegExp(/\bfoo\b/)) 
-one
source share

All Articles