在javascript中使用RegExp的Word边界正则表达式

时间:2012-06-26 17:09:29

标签: javascript

  

对任何人都没有任何人

> 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'

为什么在这种情况下使用RegExp不起作用?我需要使用它才能

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

2 个答案:

答案 0 :(得分:2)

以这种方式使用RegEx字符串时,您需要转义反斜杠:

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

答案 1 :(得分:0)

显然\b必须被转义,例如

new Regexp('\\b' + **myterm** + '\\b');
相关问题