javascript - 使用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);
解决方案
不需要正则表达式,只需遍历单词 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);
推荐阅读
- c++ - 如何将 __ramfunc 内在函数应用于构造函数?
- java - 如何处理在 Project Reactor 中订阅处理器时引发的异常
- javascript - 边缘浏览器 Ajax 文件上传调用 WebApi 不起作用
- google-cloud-platform - 当导入文件包含通配符时,gcloud sql import csv 失败并出现权限错误
- python - 如何在 Django 中获取 ForeignKey 的其他字段
- python - 当 add_time 函数必须将 sum 值传递给 print_time 时出现问题
- java - 有没有一种方法可以将月份添加到获取以下预期的日期
- google-bigquery - BiqQuery 中的大数据按分位数分组
- c# - 如果excel文件在IIS express文件夹中,则只需将其导入数据库
- rxjs - 是否可以在其他史诗运行时“跳过”执行?