【问题标题】:Check if string contain an array of keyword检查字符串是否包含关键字数组
【发布时间】:2017-12-12 16:43:03
【问题描述】:

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

我有一个字符串例如: Ok bot,给我看看 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');
}

但它不起作用

有人可以帮帮我吗?

谢谢

【问题讨论】:

    标签: javascript arrays string keyword


    【解决方案1】:

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

    您可以通过Array#filterString#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');
    }

    【讨论】:

    猜你喜欢
    • 2020-07-27
    • 2022-06-30
    • 1970-01-01
    • 2021-12-14
    • 2016-01-31
    • 2018-06-11
    • 2015-11-12
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多