Search code examples
javascriptarraysprompt

.includes() Checking for keywords in prompt()


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!");
}

Solution

  • 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!");
    }