6

I'm trying to make a function that finds the string that contains all words from an array.

I have tried this:

function multiSearchOr(text, searchWords){
    var searchExp = new RegExp(searchWords.join("|"),"gi");
    return (searchExp.test(text))?"Found!":"Not found!";
}

alert(multiSearchOr("Hello my name sam", ["Hello", "is"]))

But this only alert "Found" when one of the words have been found.

I need it to alert me when all the words are in the string.

An example:

var sentence = "I love cake"    
var words = ["I", "cake"];

I want the application to alert me when it finds all of the words from the array in the string sentence. Not when it only found one of the words.

4
  • Possible duplicate of whole word match in javascript
    – user7973034
    Jun 17, 2017 at 12:46
  • @MatthewSanetra I dont need the whole world, i need it to alert me when all of the words from array has been found in the string.
    – Samhakadas
    Jun 17, 2017 at 12:51
  • 2
    You need to iterate over array, create regex, test it and if not found return false; else return true;.
    – Tushar
    Jun 17, 2017 at 12:52
  • Count Total Amount Of Specific Word In a String JavaScript stackoverflow.com/a/65036248/4752258 Nov 29, 2020 at 19:00

5 Answers 5

10

If you're interested in using only a single regular expression, then you need to use a positive lookahead when constructing your expression. It will look something like that:

'(?=\\b' + word + '\\b)'

Given this construction, you can then create your regular expression and test for the match:

function multiSearchOr(text, searchWords){
    var regex = searchWords
        .map(word => "(?=.*\\b" + word + "\\b)")
        .join('');
    var searchExp = new RegExp(regex, "gi");
    return (searchExp.test(text))? "Found!" : "Not found!";
}
2
0

Here's a working example. You simply need to iterate over the array and compare if the words are present in the string or not using indexOf(). if it is not equal then alert Not found otherwise alert Found.

function multiSearchOr(text, searchWords){

   for(var i=0; i<searchWords.length; i++)
   {
    if(text.indexOf(searchWords[i]) == -1)
      return('Not Found!');
   }
   return('Found!');
}

alert(multiSearchOr("Hello my name sam", ["Hello", "is"]));

2
  • This is case-sensitive. OP wants to check case-insensitively.
    – Tushar
    Jun 17, 2017 at 13:21
  • @Tushar Add .toLowerCase() to the variables being passed to the function. Jun 26, 2019 at 2:26
0

Is this what are you looking for ? In this way, you can use more complex sentences that contain non-alphanumeric characters.

var sentence = "Hello, how are you ?"
var test1 = ["Hello", "how", "test"];
var test2 = ["hello", "How"];

function multiSearchOr(text, searchWords){
  if (text && searchWords) {
      var filteredText = text.match(/[^_\W]+/g);
      
      if (filteredText !== null) {
        var lowerCaseText = filteredText.map(function(word) { 
          return word.toLowerCase(); 
        });
        
        for (var i = 0; i < searchWords.length; i++) {
          if (lowerCaseText.indexOf(searchWords[i].toLowerCase()) === -1) {
            return "Not found!";
          }
        }
        
        return "Found!"
      }
    
      return "Error: the text provided doesn't contain any words!"
  }
  
  return "Error: Props are missing";
}

console.log(multiSearchOr(sentence, test1));
console.log(multiSearchOr(sentence, test2));

5
  • indexOf work case-sensitively. So, if the string contains Hello and you use hello in searchWords, your solution will not work. You can convert both strings to lowercase and then use indexOf.
    – Tushar
    Jun 17, 2017 at 13:19
  • Yes, that's true, but he never asked for this. Maybe he wants to return "Found" if the exact word was found in the sentence. Jun 17, 2017 at 13:30
  • 1
    He did, when he used i-case-insensitive flag in the Regex.
    – Tushar
    Jun 17, 2017 at 13:31
  • Good catch ! I didn't check his code. I just wrote mine :) Jun 17, 2017 at 13:35
  • Count Total Amount Of Specific Word In a String JavaScript stackoverflow.com/a/65036248/4752258 Nov 29, 2020 at 19:00
0
    if all(word in text for word in searchWords):
        print('found all')
    if any(word in text for word in searchWords):
        print('found at least one')

all() if you want that all the word in the list searchWords are in the text any() if it's enough that one list word is in the text

0

Here is a version that will split the sentense you pass and check each word

const matchAllEntries = (arr, target) => target.every(v => arr.includes(v));
const arr = ['lorem', 'ipsum', 'dolor'];
const strs = ['lorem blue dolor sky ipsum', 'sky loremdoloripsum blue', 'lorem dolor ipsum'];

strs.forEach(str => {
  // split on non alphabet and numbers (includes whitespace and puntuation)
  parts = str.split(/\W/); 
  console.log(matchAllEntries(arr, parts));
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.