javascript - 查找字符串是否包含数组的任何值的更快方法
问题描述
我喜欢找到最快的方法(除了循环数组的每个元素)来查找 a 是否$string ='hello my name is john'
包含 a 上的任何单词$array = ['none','tomatos','john']
,在这种情况下不包含任何黑名单单词$black_array = ['find','other']
在此示例中,结果应为 True。
目前我循环数组的每个元素并使用$string.search($array[i])
解决方案
实现这一点的一种方法是从每个数组中创建正则表达式并测试白名单中的匹配项和黑名单中的不匹配项:
const $string = 'hello my name is john';
const $array = ['none', 'tomatos', 'john'];
const $black_array = ['find', 'other']
const white = new RegExp('\\b(' + $array.join('|') + ')\\b');
const black = new RegExp('\\b(' + $black_array.join('|') + ')\\b');
const match = white.test($string) && !black.test($string);
console.log(match);
推荐阅读
- apache-spark - 如何避免一次又一次地重新评估pyspark数据帧上的每个转换
- javascript - 文本和语音通道计数
- android - 迭代 JSONObject 不会填充微调器
- c++ - 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- xpath - 如何启用以下 URL 功能以在我的代码中工作?
- asp.net - 在多对多关系中查看项目的详细信息
- python - 试图跨越两个数据框,一个带有值,另一个带有布尔值
- webpack - Webpack-dev-server 处理代理头
- haskell - 构造函数中的类型约束
- java - 带有硒 Java 的剑道组合框