检查字符串是否包含关键字数组
Check if string contain an array of keyword
我在互联网上找不到我需要的东西,或者可能是我没有使用正确的词,但这是我的问题。
我有一个字符串,例如:
好的机器人,给我看看 Foo 程序的文档。
还有我的关键字:["bot","doc", "show", "Foo"]
我希望如果字符串包含 3 个或更多关键字,我的函数将 return 例如一条消息
我考虑过
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
函数,它 returns 数组中的项目索引。在您的情况下,您正在检查数组关键字中的 message
这在逻辑上是错误的条件
您可以通过Array#filter and 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');
}
我在互联网上找不到我需要的东西,或者可能是我没有使用正确的词,但这是我的问题。
我有一个字符串,例如: 好的机器人,给我看看 Foo 程序的文档。
还有我的关键字:["bot","doc", "show", "Foo"]
我希望如果字符串包含 3 个或更多关键字,我的函数将 return 例如一条消息
我考虑过
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
函数,它 returns 数组中的项目索引。在您的情况下,您正在检查数组关键字中的 message
这在逻辑上是错误的条件
您可以通过Array#filter and 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');
}