Skip to content

javascript : Check if there is an array member in the entered text

I have an array of words and I want to check the entered text so that if one of the array elements is in this text, it will show me that element

and in this function I want to check it:

exports.words = (text)=>{
        const words = [
                'word1' , 
                'word2' , 
                'word3' , 
                'word4'
        ];
        for (let i = 0; i < words.length; i++) {
            const el = words[i];
            if(el.includes(text)){
                return el;
            }else{
                return 'no words'
            }
        }
}

the problem is this function just return the first element (word1) And if I enter word2 or word3 in text, it returns ‘no words’, even though it is in the array

so how can I fix this problem?

Answer

The issue is in the else block inside the loop, the function is returning after executing the first iteration.

You should return no words from out side of the for loop which will guarantee the full loop execution if no match found:

var words = (text)=>{
  const words = ['word1','word2','word3','word4'];
  for (let i = 0; i < words.length; i++) {
      const el = words[i];
      if(el.includes(text)){
          return el;
      }      
  }
  return 'no words'; //return here
}

console.log(words('word2')); //word2
console.log(words('other')); //no words