.includes() Checking for keywords in prompt()

时间秒杀一切 提交于 2020-07-09 03:30:40

问题


I'm creating a sort of chatbot which will run on imbedded keywords stored in arrays, in this example I have array x being checked in y. This returns true whenever I exactly type Hello in the prompt(). However if I were to say something along the lines of "Oh Hello There." in the prompt, it returns false. How can I check for keywords in an array within a prompt() (in-between sentences)

var x = ['Hello', 'Hi', 'Sup'];
var y = prompt("Looking for a Hello...");

if (x.includes(y)){
    alert("You Said Hello!");
} else {
    alert("No Hello Found!");
}

回答1:


You would need to either check for each word, or use a Regular Expression like in this snippet

var x = ['Hello', 'Hi', 'Sup'];
var y = prompt("Looking for a Hello...");

var containsX = x.some(word=>y.includes(word))

if (containsX){
    alert("You Said Hello!");
} else {
    alert("No Hello Found!");
}



回答2:


Try to use indexof.

As mdn says:

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

let x = ['Hello', 'Hi', 'Sup'];
let y = "Looking for a Hello...";

console.log(x.some(s=> y.indexOf(s)));


来源:https://stackoverflow.com/questions/59128785/includes-checking-for-keywords-in-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!