tofutim
tofutim

Reputation: 23384

Word boundary regex with RegExp in javascript

Owe no one anything to another

> str.replace(/\bno\b/g, 'yes');
'Owe yes one anything to another'

> str.replace(new RegExp('\bno\b','g'),'yes');
'Owe no one anything to another'

Why does using RegExp not work in this case? I need to use it so that I can

var regex = new RegExp('\b'+ **myterm** +'\b','g');  or
var regex = new RegExp('(^|\s)'+ **myterm** +'(?=\s|$)','g');

Upvotes: 1

Views: 71

Answers (2)

tofutim
tofutim

Reputation: 23384

Apparently the \b had to be escaped, e.g.,

new Regexp('\\b' + **myterm** + '\\b');

Upvotes: 0

mVChr
mVChr

Reputation: 50215

You need to escape your backslashes when using a RegExp string in this way:

str.replace(new RegExp('\\bno\\b', 'g'), 'yes');

Upvotes: 2

Related Questions