javascript - 来自变量的正则表达式 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
.
解决方案
使用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");
}
推荐阅读
- javascript - 在 React 中设置 SVG 路径
- amazon-web-services - 在 AWS Step Function 的并行状态下,如果一个分支出现故障,是否有办法确保其他分支继续运行直到完成?
- javascript - Cordova:如何使用 vanilla JS 保存文本文件
- ruby-on-rails - google-cloud-logging 中的记录器不适用于 rails
- angular - 当我在带有 dc.js 的 Angular 中使用饼图时,它没有被渲染
- vue.js - 使用 Apollo 和 Vuejs 的反应式查询定义
- storybook - 汇总并将我的样式文件夹中的所有内容构建到样式表并将其插入到 html
- c++ - Enterprise Architect 15.1 无法识别 C++ 模板
- paypal - “提交按钮”按钮上缺少 PayPal 按钮标签
- google-cloud-dataflow - 限制光束管道 AvroIO.write() 中每个分片的记录数