Home > OS >  Why doesn't 'in' works for checking if a specific word is in an array in JavaScript [
Why doesn't 'in' works for checking if a specific word is in an array in JavaScript [

Time:09-25

So, basically I'm working with string manipulation for a chatbot. When it returns a string from a message, I'm just checking if there's an specific word on it:

let msg = 'how are you?'                     //Message example
let words = msg.split(' ')                   //Words spliting
if ('are' in words) {}                       //This is where I'm having the problem

I know that in works for when I check a number inside of an array, but it doesn't seem to work with strings. Is there a different way to call it when it's about strings? I could do the checking using a loop, then a if (words[i] === 'are') {}, but I'd like to avoid that, if possible.

CodePudding user response:

You can use includes:

if(words.includes('are')) { }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

CodePudding user response:

You can use words.includes("are"). Check the live demo:

let msg = 'how are you?'                     //Message example
let words = msg.split(' ')                   //Words spliting
console.log(words);
if (words.includes("are")) {
   console.log('exist');
} else {
   console.log('not exist');
}

  • Related