首页 > 解决方案 > 使用Javascript以任何顺序使用正则表达式查找字符串中的所有匹配项

问题描述

如何在下面找到所有匹配项?我现在得到它的方式,它会从关键字数组中找到任何匹配项,但是,由于存在单词“not”,因此控制台中的匹配项应该是空的。

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (title.search(new RegExp(keywords.join("|"),"i")) != -1) {
     matches.push(title);
}
console.log(matches);

标签: javascript

解决方案


不需要正则表达式,只需遍历单词 using every(),并检查每个关键字 using includes()(见下文);

console.log(Check("How to edit an image", ["image","edit","not"])); // false
console.log(Check("How to edit an image", ["image","edit"]));       // true

function Check(title, keywords) {
    return keywords.every(word => title.indexOf(word) > -1);
}

注意:按照 OP 的要求使用title.indexOf(word) > -1来支持 IE 11。


编辑; 基于OP的评论;

"not"从数组中删除keywords以确保逻辑正常工作

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (keywords.every(word => title.indexOf(word) > -1)) {
     matches.push(title);
}
console.log(matches);


推荐阅读