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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:49:52  来源:igfitidea点击:

JavaScript regex test if string contains specific word (with variable)

javascriptregexstring-comparison

提问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 RegExpdoes 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/.