为了在JS中构建一个小型的chabot,我需要检查列表中的一个单词是否在字符串中,如下所示:
var helloWords = [" hello"," salut"," hi"," yo","嘿&#34 ];
var HowWords = ["你好吗","什么'","它是怎么回事","怎么做你做"];
如果"其中一个来自helloWords的单词在字符串"
中- >回复一些事情
如果" howWords中的一个词出现在字符串"
中- >回复别的东西
我目前正在使用以下方法,但它根本不实用,而且我在长期的if / else计划中迷路了...
var hello = /\bhello\b|\bhi\b|\byo\b|\bsalut\b/gi.test(commands);
if(hello == true} ....
你知道是否有更清洁,更有效的方法来构建这样的东西?也许在另一个语言中?
非常感谢!
答案 0 :(得分:3)
您可以使用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
}
答案 1 :(得分:1)
我建议您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”时才有效,但是如果字符串是“你好”,它就不起作用了。
另一种方法是使用函数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');
}