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.

4
  • 1
    Please read the documentation on the in operator. Commented Sep 24, 2021 at 15:59
  • Because strings can be keys (property names) of objects, and that is the purpose of the in operator. Commented Sep 24, 2021 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. Commented Sep 24, 2021 at 15:59
  • allright, thanks for the explaining Commented Sep 24, 2021 at 16:00

2 Answers 2

1

You can use includes:

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

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

Sign up to request clarification or add additional context in comments.

Comments

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');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.