-6

I need to compare the word from the string in jQuery. In short each word is in the string then match should be true, otherwise not. It doesn't matter what sequence.

For example if I have the sentence: I need to Visit W3Schools

If I search need w3school ==> Match
If I search need go w3school ==> Not Match
If I search w3schools visit ==> Match
If I search need go ==> Not Match

It can be multiple words like 1, 2 or more than 2.

I used

var keyword = "I need to Visit W3Schools";

if(keyword.indexOf('need w3school') != -1){
   console.log('Found');
}else{
    console.log('Not Found');
}

But it works only subsequent word not other case "w3schools visit".

Dhaval
  • 89
  • 2
  • 11
  • What if the user doesn't put whitespace between words?? – Ryan Wilson Jun 13 '18 at 16:45
  • 3
    Firstly, please show the code you wrote in an effort to solve this yourself. Remember that we are here to help you debug issues with existing code, not to write code for you. Secondly, I know you only mentioned them in passing, but don't use W3Schools. Their articles are often outdated and sometimes just plain wrong. MDN is a much better resource for HTML, JS and CSS. – Rory McCrossan Jun 13 '18 at 16:46
  • 3
    Pure code-writing requests are off-topic on Stack Overflow — we expect questions here to relate to *specific* programming problems — but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. – j08691 Jun 13 '18 at 16:46
  • 1
    This is a logical javascipt problem, *not* a jQuery problem. – Taplar Jun 13 '18 at 16:46
  • Is case-sensitivity important? – Jonathan Rys Jun 13 '18 at 16:54
  • So you would need to search each word..... – epascarello Jun 13 '18 at 16:55
  • @Jonathan Rys - No case sensitivity not important. – Dhaval Jun 13 '18 at 16:57
  • Possible duplicate of [How to search for multiple texts in a string, using java script?](https://stackoverflow.com/q/16851094) – Munim Munna Jun 13 '18 at 22:26

1 Answers1

2
//Function CheckForWords accepts the text value
//Splits text value on whitespace, iterates each word,
//Checks if each word is found in text, if not returns false
function CheckForWords(text){
   const words = text.split(' ');

   for(let x = 0; x < words.length; x++){
        if(text.toLowerCase().indexOf(words[x].toLowerCase()) === -1){
            return false;
        }
   }

   return true;
}
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40