这很难解释,所以我只举一个例子。 我有一系列特定的关键字,如下所示:
const keywordArr = ['jim', 'john'];
然后我有一个字符串:
const message = 'Hello john, how are you doing today?'
我想检查 message
是否包含 keywordArr
中的值。我知道我可以循环遍历 keywordArr
中的每个值并像这样检查:
keywordArr.forEach(function(word) {
if (message.toLowerCase().includes(word)) {
rest of code here..
}
}
但是,我每秒收到大约 5 条消息,因此该方法非常消耗性能。有什么有效的方法可以做到这一点吗?
最佳答案
您可以使用forEach()
对于数组和 match()
检查字符串是否包含。
演示
const keywordArr = ['jim', 'john'],
message = 'Hello john, how are you doing today?';
keywordArr.forEach(v => {
if (message.match(v)) console.log(`message contain ${v}`);
});
关于javascript - node.js 如何在字符串中搜索数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49636181/