问题
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