Samhakadas
Samhakadas

Reputation: 103

Searching for words in string

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.

Upvotes: 6

Views: 16817

Answers (5)

mplungjan
mplungjan

Reputation: 177691

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));
})

Upvotes: 0

DavideMessori
DavideMessori

Reputation: 1

    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

Upvotes: 0

ValentinVoilean
ValentinVoilean

Reputation: 1382

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));

Upvotes: 0

Mateusz Kocz
Mateusz Kocz

Reputation: 4602

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!";
}

Upvotes: 10

Raj
Raj

Reputation: 2028

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"]));

Upvotes: 0

Related Questions