我正在映射一个单词列表(也有随机字符(,但正则表达式似乎不起作用,最终抛出错误。 我基本上有一个常量变量(称为content
( 我想搜索以查看content
变量中是否有某些单词。
所以我有
if (list.words.map(lword=> {
const re = new RegExp("/" + lword+ "\/g");
if (re.test(content)) {
return true;
}
}
但这只是失败了,什么也抓不到。我收到一个Nothing to repeat
错误。 具体来说:Uncaught SyntaxError: Invalid regular expression: //Lu(*/g/: Nothing to repeat
我不确定如何搜索content
以查看它是否包含lword
.
当你使用new RegExp()
时,你不会把分隔符和修饰符放在字符串中,只放在表达式中。修饰符位于可选的第二个参数中。
const re = new RegExp(lword, "g");
如果要将lword
视为要搜索的文本字符串,而不是正则表达式模式,则首先不应使用RegExp
。只需用indexOf()
搜索它:
const list = {
words: ["this", "some", "words"]
};
const content = "There are some word here";
if (list.words.some(lword => content.indexOf(lword) != -1)) {
console.log("words were found");
}