Skip to content Skip to sidebar Skip to footer

Regex - Javascript .match() With A Variable Keyword

I have a string with keywords, separated by comma's. Now I also have a nice RegEx, to filter out all the keywords in that string, that matches a queried-string. Check out this init

Solution 1:

Here's a general solution for use with regexes:

var query = "anything";    

// Escape the metacharacters that may be found in the query// sadly, JS lacks a built-in regex escape function
query = query.replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');

var regex = newRegExp("someRegexA" + query + "someRegexB", "g");

As long as someRegexA and someRegexB form a valid regex with a literal in-between, the regex variable will always hold a valid regex.

But, in your particular case, I'd simply do this:

var query = "car";
var items = masterString.split(",");
query = query.toLowerCase();
for (var i = 0; i < items.length; ++i) {
    if (items[i].toLowerCase().indexOf(query) >= 0) {
        console.log(items[i]);
    }
}

Solution 2:

How about this one?, you only need to replace \ \ with String , and it works for me. it can find whether your string has "car", not other similar word

var query  = 'car';
 varstring = "car,bike,carrot,plane,card";
 var strRegEx = '[^,]*'+query+'[,$]*'; 
 string.match(strRegEx);

Post a Comment for "Regex - Javascript .match() With A Variable Keyword"