首页 > 解决方案 > 查找字符串是否包含数组的任何值的更快方法

问题描述

我喜欢找到最快的方法(除了循环数组的每个元素)来查找 a 是否$string ='hello my name is john'包含 a 上的任何单词$array = ['none','tomatos','john'],在这种情况下不包含任何黑名单单词$black_array = ['find','other']

在此示例中,结果应为 True。

目前我循环数组的每个元素并使用$string.search($array[i])

标签: javascriptarrays

解决方案


实现这一点的一种方法是从每个数组中创建正则表达式并测试白名单中的匹配项和黑名单中的不匹配项:

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


推荐阅读