george
george

Reputation: 3221

Regex Javascript use variable within pattern

I know that this's been asked before but none of the suggested solutions worked for me. I've got the following:

  var regex = new RegExp(/D0030001 IN/gi);
  $("p").filter(function () {
        return regex.test(this.id); 
   }).css("background-color","blue");

This one works fine. However, when I try to do

 spl = [];
 spl[0] = "D0030001";
 spl[1] = "IN";
 var regex = new RegExp("/" + spl[0] + " " + spl[1] + "/gi");
       $("p").filter(function () {
        return regex.test(this.id); 
   }).css("background-color","blue");

This one doesn't work. In other words I need to use variables to construct the regex pattern. Thanks

Upvotes: 0

Views: 41

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

You need to use the second argument of RegExp constructor to set the flags and you don't need / / delimiters.

var regex = new RegExp(spl[0] + " " + spl[1], "gi");

Upvotes: 2

Related Questions