javascript - 检查字符串是否包含关键字数组

标签 javascript arrays string keyword

我在互联网上找不到我需要的东西,或者可能是我没有使用正确的词语,但这是我的问题。

我有一个字符串例如: 好的机器人,给我看看 Foo 程序的文档。

这是我的关键字:["bot","doc", "show", "Foo"]

我希望如果字符串包含 3 个或更多关键字,我的函数将返回一条消息,例如

我考虑过

var message = "Ok bot, show me the doc of the Foo program.";
var keywords = ["bot","doc","show","foo"];
if(keywords.indexOf(message) >=3 ){
  console.log('ok I understand');
}

但它不起作用

有人可以帮我吗?

谢谢

最佳答案

您正在调用 indexOf 函数,该函数返回数组中的项目索引。在您的情况下,您正在检查数组关键字中的message,这在逻辑上是错误的条件

您可以通过 Array#filter 过滤找到的关键字和 String#includes然后检查它们的长度。

var message = "Ok bot, show me the doc of the Foo program.";
var keywords = ["bot","doc","show","foo"];

var keywordsFound = keywords.filter(item => message.includes(item));

if(keywordsFound.length >= 3 ) {
  console.log('ok I understand');
}

关于javascript - 检查字符串是否包含关键字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777545/

相关文章:

javascript - 使用 setInterval 更新 .style 属性

javascript - Safari 浏览器的视频录制

javascript - 将数组拆分为固定的 n 个具有动态大小的 block

java - 提取字符串的数字模式并将其放入对象中

ios - 不区分大小写的字符串搜索 - iphone

javascript - React 不会在 Safari 或 IE 或任何移动网络浏览器中加载图像

javascript - webpack 的 import() 什么时候不会创建新文件?

c - 字符串修剪导致内存泄漏?

arrays - SwiftyJSON 将新数据附加到现有 JSON 数组

c++ - C++候选函数不可行: no known conversion from 'int' to 'int *' for 1st argument; take the address of the argument with &