使用正则表达式以Javascript的任何顺序查找字符串中的所有匹配项



如何查找下面的所有匹配项?按照我现在的方法,它从关键字数组中找到任何匹配项,但是,由于单词"而不是";存在,则控制台中的匹配项应为空。

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);

不需要正则表达式,只需使用every()循环遍历单词,并使用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的评论;

keywords阵列中删除"not"以确保逻辑工作

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);

您不需要regex。只需映射关键字

const output= keywords.map(x=>
title.indexOf(x)!==-1 ? title : ""
);
//output
["How to edit an image", "How to edit an image", ""]

使用这个答案作为参考,如果你固定使用Regex,你应该使用查找:

^(?=.*bimageb)(?=.*beditb)(?=.*bnotb).*$

应用于您的Javascript代码,它将类似于:

var title = "How to edit an image";
var title2 = "How to not edit an image";
var keywords = ["image","edit","not"];
var matches = [];
// Using for block because I don't remember if forof, forin or foreach are supported by IE 11
var regex = "^";
for (var i = 0; i < keywords.length; i++) {
regex += "(?=.*\b" + keywords[i] + "\b)"; // Needed beacuse template Strings are not supported by IE 11.
}
regex += ".*$"
if (title.search(new RegExp(regex,"i")) != -1) {
matches.push(title);
}
console.log(matches);
if (title2.search(new RegExp(regex,"i")) != -1) {
matches.push(title2);
}
console.log(matches);

最新更新