Rajesh
Rajesh

Reputation: 181

Words exists in string using javascript

I need to check the words exist in string using javascript OR jquery.

For ex String: I need to Visit W3Schools
if I check "need w3school"==> True
if I check "need go w3school"==> False
if I check "w3schools visit"==> True
if I check "need go "==> False

It can be multiple word like 1,2 or more than 2. In short it should return "TRUE" if all the words exist in string otherwise "FALSE". Doesn't matter the sequence.

var dat=[];
if(str.indexOf($('#search').val()) != -1){
    dat[] = {name:str};
}

Upvotes: 0

Views: 76

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

Try following

let str = "I need to Visit W3Schools";
str = str.toLowerCase();

function check(s) {
  return s.toLowerCase().split(" ").every(x => str.includes(x));
}
console.log(check("need w3school"));
console.log(check("need go w3school"));
console.log(check("w3schools visit"));
console.log(check("need go "));

Upvotes: 2

Related Questions