8
我要檢查一個正則表達式,如果一個字符串包含特定單詞的JavaScript正則表達式測試。它按預期工作:如果字符串包含特定單詞(可變)
/\bword\b/.test('a long text with the desired word amongst others'); // true
/\bamong\b/.test('a long text with the desired word amongst others'); // false
但我需要在變量中檢查的字。使用new RegExp
不能正常工作,它總是返回false
:
var myString = 'a long text with the desired word amongst others';
var myWord = 'word';
new RegExp('\b' + myWord + '\b').test(myString); // false
myWord = "among";
new RegExp('\b' + myWord + '\b').test(myString); // false
這裏有什麼問題?
+1,看到http://jsfiddle.net/TxQ7c/6/ – 2012-04-10 18:06:54
你發佈你的答案,同時想通了。謝謝。不知道是什麼有這個答案要做到: – Alp 2012-04-10 18:10:55
\ B就不會與所有的語言 – Uri 2016-10-21 17:17:10