0

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.

  • 1
    Please read the documentation on [the `in` operator](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in). – Sebastian Simon Sep 24 '21 at 15:59
  • Because strings can be keys (property names) of objects, and that is the purpose of the `in` operator. – Heretic Monkey Sep 24 '21 at 15:59
  • 1
    *"I know that `in` works for when I check a number inside of an array"* It doesn't. `in` operator checks if the object has the given key. You are probably doing something like `if(1 in [1,2,3])`. It returns true because the array has the key `1`. If you do `if (1 in [2,3,4])`, that ALSO returns true because it doesn't check the value, but the keys of the array. – adiga Sep 24 '21 at 15:59
  • allright, thanks for the explaining – Robson Luan Sep 24 '21 at 16:00

2 Answers2

1

You can use includes:

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

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

Joao Leal
  • 5,533
  • 1
  • 13
  • 23
1

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');
}
Tuan Dao
  • 2,647
  • 1
  • 10
  • 20