检查单词列表是否在字符串中(小型聊天机器人)

Check if a list of words is in a string (Small Chatbot)

为了在 JS 中构建一个小型聊天机器人,我需要检查我放在列表中的单词是否在字符串中,如下所示:

var helloWords = ["hello", "salut", "hi", "yo", "hey"];

var HowWords = ["how are you", "what's up", "how is it going", "how do you do"];

If "one of the words from helloWords is in the string"

-> Reply something

If "one of the words from howWords is in the string"

-> Reply something else

我目前正在使用下面的方法,但它根本不实用,我迷失在一个漫长的 if/else 程序中...

var hello = /\bhello\b|\bhi\b|\byo\b|\bsalut\b/gi.test(commands);

if (hello == true} ....

你知道是否有一种更干净、更有效的方法来构建这样的东西吗?也许用其他语言?

非常感谢!

您可以使用 Array.prototype.includes().

要匹配整个字符串:

var helloWords = ["hello", "salut", "hi", "yo", "hey"];

var HowWords = ["how are you", "what's up", "how is it going", "how do you do"];

if (helloWords.includes(yourString.toLowerCase())) {
    // Reply something
}
if (HowWords.includes(yourString.toLowerCase())) {

    // Reply something else
}

要匹配部分字符串,您需要使用 Array.prototype.some():

var helloWords = ["hello", "salut", "hi", "yo", "hey"];

var HowWords = ["how are you", "what's up", "how is it going", "how do you do"];

if (helloWords.some( i => yourString.toLowerCase().includes(i) )) {
    // Reply something
}
if (HowWords.some( i => yourString.toLowerCase().includes(i) )) {
    // Reply something else
}

我推荐你 indexOf 以获得更广泛的浏览器兼容性:

var helloWords = ["hello", "salut", "hi", "yo", "hey"];
var HowWords = ["how are you", "what's up", "how is it going", "how do you do"];

if (helloWords.indexOf(yourString.toLowerCase()) !== -1) {
// Logic
}
if (HowWords.indexOf(yourString.toLowerCase()) !== -1) {
// Logic
}

Hello, thank you for the help. But I've got a problem, it's working only when there's only the word (exemple) "hello" but if the string is "hello you" it's not working.

另一种方法是使用函数 some:

var helloWords = ["hello", "salut", "hi", "yo", "hey"];
var HowWords = ["how are you", "what's up", "how is it going", "how do you do"];

var input = 'hello you',
    samples = input.split(/\s+/g); // split the entered value by spaces.
if (helloWords.some((h) => samples.includes(h.trim().toLowerCase()))) {
  console.log('Logic for helloWords');
}

// This condition returns false because neither 'hello' nor 'you' is within
// the array HowWords.
if (HowWords.some((h) => samples.includes(h.trim().toLowerCase()))) {
  console.log('Logic for HowWords');
}