Skip to content Skip to sidebar Skip to footer

Regex Javascript - Match Multiple Search Terms Ignoring Their Order

I would like to find all the matches of given strings (divided by spaces) in a string. (The way for example, iTunes search box works). That, for example, both 'ab de' and 'de ab' w

Solution 1:

Returns true when all parts (divided by , or ' ') of a searchString occur in text. Otherwise false is returned.

filter(text, searchString) {
    const regexStr = '(?=.*' + searchString.split(/\,|\s/).join(')(?=.*') + ')';
    const searchRegEx = newRegExp(regexStr, 'gi');
    return text.match(searchRegEx) !== null;
}

Solution 2:

I'm pretty sure you could come up with a regex to do what you want, but it may not be the most efficient approach.

For example, the regex pattern (?=.*bc)(?=.*e)(?=.*a) will match any string that contains bc, e, anda.

var isMatch = 'abcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals truevar isMatch = 'bcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals false

You could write a function to dynamically create an expression based on your search terms, but whether it's the best way to accomplish what you are doing is another question.

Solution 3:

Alternations are order insensitive:

"abcde".match(/(ab|de)/g); // => ['ab', 'de']"abcde".match(/(de|ab)/g); // => ['ab', 'de']

So if you have a list of words to match you can build a regex with an alternation on the fly like so:

functionregexForWordList(words) {
  returnnewRegExp('(' + words.join('|') + ')', 'g');
}
'abcde'.match(['a', 'e']); // => ['a', 'e']

Solution 4:

Try this:

var str = "your string";
str = str.split( " " );
for( var i = 0 ; i < str.length ; i++ ){
    // your regexp match
}

Solution 5:

This is script which I use - it works also with single word searchStrings

var what="test string with search cool word";
var searchString="search word";
var search = newRegExp(searchString, "gi"); // one-word searching// multiple search wordsif(searchString.indexOf(' ') != -1) {

    search="";
    var words=searchString.split(" ");

    for(var i = 0; i < words.length; i++) {

        search+="(?=.*" + words[i] + ")";

    }

    search = newRegExp(search + ".+", "gi");

}

if(search.test(what)) {

    // found

} else {

    // notfound

}

Post a Comment for "Regex Javascript - Match Multiple Search Terms Ignoring Their Order"