El Bandito
El Bandito

Reputation: 55

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 initial question - RegEx - Extract words that contains a substring, from a comma seperated string

The example below works fine; it has a masterString, and a resultString. That last one only contains the keywords that has at least the word "car" in it.

masterString = "typography,caret,car,align,shopping-cart,adjust,card";
resultString = masterString.match(/[^,]*car[^,]*/g);
console.log(resultString);

Result from the code above;

"caret", "car", "shopping-cart", "card"

But how can I use the RegEx, with a variable matching-word (the word "car" in this example static and not variable).

I think it has to do something with a RegExp - but I can't figure out...

Upvotes: 2

Views: 5807

Answers (3)

brasofilo
brasofilo

Reputation: 26065

Answer provided by OP and removed from inside the question

I figured out this quick-and-maybe-very-dirty solution...

var query  = 'car';
var string = "car,bike,carrot,plane,card";
var regex  = new RegExp("[^,]*|QUERY|[^,]*".replace('|QUERY|',query),'ig');
string.match(regex);

This code outputs the following, not sure if it is good crafted, 'though..

"car", "carrot", "card"

But ended figuring out another, much simpler solution;

var query  = "car";
var string = "car,bike,carrot,plane,card";
string.match(new RegExp("[^,]*"+query+"[^,]*",'ig'));

This code outputs the string below;

["car", "carrot", "card"]

My app-search-engine now works perfect :)

Upvotes: 0

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51340

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 = new RegExp("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]);
    }
}

Upvotes: 2

Will
Will

Reputation: 211

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';
 var string = "car,bike,carrot,plane,card";
 var strRegEx = '[^,]*'+query+'[,$]*'; 
 string.match(strRegEx);

Upvotes: 1

Related Questions