首页 > 解决方案 > 来自变量的正则表达式 javascript 混淆

问题描述

我正在映射单词列表(也包含随机字符),而正则表达式似乎不起作用并最终引发错误。我基本上有一个 const 变量(称为),我想搜索该变量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.

标签: javascriptregexiterationmapping

解决方案


使用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");
}


推荐阅读