Arya Anish
Arya Anish

Reputation: 660

Check whether string contains other than specific word

I need to check whether a string contains other than the specified words/sentence (javascript), it will return true if:

Thank you!

Upvotes: 0

Views: 90

Answers (3)

mplungjan
mplungjan

Reputation: 177860

Yes you can replace all not in the array

const arr = ["ANOTHER CMD","8809 8805", "8809 8805"]
const okContent = str => { 
  arr.forEach(entry => str = str.replaceAll(entry,""))
  return str.trim()==="";
};

console.log(okContent('Has other stuff than ANOTHER CMD and 8809 8805'))
console.log(okContent('8809 8805 ANOTHER CMD 8809 8805'))

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 491

you can try regex!

use your array of strings as the '|' separated regex value

and check the specified string in the given line. if it presents negate the output.

const regex = /(ANOTHER CMD|8809 8805|8806 8807)/i
console.log(!regex.test('Should not contain word ANOTHER CMD'))

console.log(regex.test('Should contain word ANOTHER CMD'))

Upvotes: 0

Arya Anish
Arya Anish

Reputation: 660

I don't know if it's the correct way of doing it but this worked for me:

  • replace all the valid words with balnk (using replace)
  • check if the string is left empty
  • if it's empty, it means that the string does not contain any unwanted string (to check for space you could use trim method)

Upvotes: 0

Related Questions