为了在 JS 中构建一个小 chabot,我需要检查我放在列表中的单词之一是否在字符串中,如下所示:
var helloWords = ["hello", "salut", "hi", "yo", "hey"];
var HowWords = [“你好吗”,“最近怎么样”,“最近怎么样”,“你怎么样”];
如果“来自 helloWords 的单词之一在字符串中”
-> 回复一些东西
如果“来自 howWords 的单词之一在字符串中”
-> 回复别的东西
我目前正在使用下面的方法,但它根本不实用,而且我在一个很长的 if/else 程序中迷路了......
var hello = /\bhello\b|\bhi\b|\byo\b|\bsalut\b/gi.test(commands);
如果(你好 == 真} ....
你知道是否有一种更干净、更有效的方法来构建这样的东西?也许用另一种语言?
非常感谢 !
您可以使用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
}
Run Code Online (Sandbox Code Playgroud)
要匹配部分字符串,您需要使用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
}
Run Code Online (Sandbox Code Playgroud)