繁体   English   中英

正则表达式javascript变量的混乱

[英]Regex javascript confusion from variable

我正在通过单词列表(也有随机字符)进行映射,而正则表达式似乎不起作用,并最终引发错误。 我基本上有一个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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM