JavaScript regex 测试字符串是否包含特定单词(带变量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10093955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript regex test if string contains specific word (with variable)
提问by Alp
I have a regex to check if a string contains a specific word. It works as expected:
我有一个正则表达式来检查字符串是否包含特定单词。它按预期工作:
/\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
But i need the word which is about to be checked in a variable. Using new RegExp
does not work properly, it always returns 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
What is wrong here?
这里有什么问题?
回答by
var myWord = 'word';
new RegExp('\b' + myWord + '\b')
You need to double escape the \
when building a regex from a string.
\
从字符串构建正则表达式时,您需要双重转义。
This is because \
begins an escape sequence in a string literal, so it never makes it to the regex. By doing \\
, you're including a literal '\'
character in the string, which makes the regex /\bword\b/
.
这是因为\
在字符串文字中开始一个转义序列,所以它永远不会进入正则表达式。通过这样做\\
,您'\'
在字符串中包含了一个文字字符,这使得正则表达式/\bword\b/
.