2012-06-26 292 views
1

爲什麼使用正則表達式在這種情況下無法工作不欠任何人任何東西到另一個用正則表達式字邊界正則表達式在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' 

?我需要使用它,這樣我可以

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

'「\ b」'是[backspace character(U + 0008)](http://www.fileformat.info/info/unicode/char/0008/index.htm)如果你想要反斜槓和ab('「\\ b」') – Esailija

回答

2

你需要以這種方式使用正則表達式字符串時逃避你的反斜線:

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

顯然,\b已經進行轉義,例如,

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

再次?什麼時候第一次逃脫? '\ b'不是一個轉義的'b'。 – gdoron

+0

好點 - 編輯。 – tofutim