node.js 如何在字符串中的数组中搜索值

node.js How to search for a value in an array in a string

这很难解释,所以我只举个例子。 我有一组特定的关键字,如下所示:

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 条消息,因此该方法会非常耗费性能。有什么有效的方法吗?

使用 RegExp.test() (regex101 示例检查数组是否包含任何单词)。

const keywordArr = ['jim', 'john'];

const message = 'Hello john, how are you doing today?'

const pattern = new RegExp(`\b${keywordArr.join('|')}\b`, 'gi');
const contains = pattern.test(message);

console.log(contains);

Return true/false

我们可以使用 reduceincludes 来做到这一点,如果您不喜欢整个 RegExp 事情:

const keywordArr = ['jim', 'john'];

const message = 'Hello john, how are you doing today?'

let has = keywordArr.reduce((r,v) => message.toLowerCase().includes(v.toLowerCase()) || r, false)

console.log(has)

这将匹配不区分大小写。如果您想要区分大小写的匹配项,请删除这两个 toLowerCaser() 方法。

Return一个名字

我们可以通过添加 && v 来修改 reduce 函数,这将 return 值而不是 true/false 值。我们还将把起始值从 false 修改为空字符串。

const keywordArr = ['jim', 'john'];

const message = 'Hello john, how are you doing today?'

let name = keywordArr.reduce((r,v) => message.toLowerCase().includes(v.toLowerCase()) && v || r, '')

console.log(name)

Return 一组名称

如果我们想要 return 字符串中所有名称的列表,我们可以将 && v 替换为 && r.concat(v) 然后将起始值从空字符串替换为空数组.

const keywordArr = ['jim', 'john', 'paul'];

const message = 'Hello john, how are you doing today? -- jim'

let names = keywordArr.reduce((r,v) => message.toLowerCase().includes(v.toLowerCase()) && r.concat(v) || r, [])

console.log(names)

您可以使用 forEach() for array and 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}`);
});