yunjae123 yunjae123 - 18 days ago 7
Javascript Question

my isStopWord function thinks "cat" and "catnip" are the same words

I'm trying to write a simple function that takes in a word and a stopword to see if they are the same words. It will return true if they are.
So far, by doing this,

function isStopWord(word, stopWords) {
return (stopWords.indexOf(word) !== -1);
}

console.log(isStopWord("cat", "cat"));


returns true, but doing this

console.log(isStopWord("cat", "catnip");


Also returns true... Now, I don't think I know well enough as to how ".indexOf" works to figure out why it returns true in both cases. Can anyone help me fix this function so that it knows if it's the same word and not just from the first three letters? Because doing this,

console.log(isStopWord("catnip", "cat");


returns false, so i'm a little bit confused.
Thanks!

Answer

The String.prototype.indexOf() method returns the position of the first occurrence of a specified value in a string. Thus cat has one occurence inside catnip thus the index returned will be !== 1

If you just want to check one word to another one. Use the following snippet.

function isStopWord(word, stopWords) {
  return stopWords === word;
}

console.log(isStopWord("cat", "cat"));
console.log(isStopWord("catnip", "cat"));

If you want to see if a word is present inside an array of words, use the following snipper which is using Array.prototype.indexOf()

function isStopWord(word, stopWords) {
  return stopWords.indexOf(word) !== -1;
}

console.log(isStopWord("cat", ["cat", "dog", "bird"]));
console.log(isStopWord("catnip", ["cat", "dog", "bird"]));

Comments