Javascript: String.match () - pass a string variable in a regular expression

I tried to rewrite the method (part of the tutorial in w3schools).

The problem is that the variable string becomes part of the regular expression.

Tutorial Code Example:

function myFunction() { var str = "The rain in SPAIN stays mainly in the plain"; var res = str.match(/ain/gi); console.log(res) } 

I tried:

 function myFunction() { var str = "The rain in SPAIN stays mainly in the plain"; var test = "ain"; var re = "/"+test+"/gi"; var res = str.match(re); console.log(res); } 

The way I tried did not help.

+7
javascript string
source share
5 answers

Use the regex constructor, for example:

 function myFunction() { var str = "The rain in SPAIN stays mainly in the plain", test = "ain", re = new RegExp(test, 'gi'), res = str.match(re); console.log(res); } 
+11
source share

You need to use the RegExp constructor if you want to pass the value of the variable as a regular expression.

 var test = "ain"; var re = new RegExp(test, "gi"); 

If your variable contains special characters, it is best to avoid them.

 var re = new RegExp(test.replace(/(\W)/g, "\\$1"), "gi"); 
+7
source share

Yes match() does not work with string literals

You can use var re = new RegExp(test,"gi");

  var str = "The rain in SPAIN stays mainly in the plain"; var test = "ain"; var re = new RegExp(test,"gi"); var res = str.match(re); console.log(res); 
+5
source share

You could search for "dynamic regular expressions" and you would find: Dynamically generating Javascript Regexp from variables? Or Use a dynamic (variable) string as a regular expression pattern in JavaScript , which both describe it very well.

+5
source share

Note that you pass the string to match . If we follow the documentation , new RegExp(test) will do this. Therefore, you should avoid the lines / and /gi and add the appropriate flags to the RegExp constructor: the default constructor does not add a global search ( g ) or case insensitive to case ( i ).

So the solution to your problem:

 var str = "The rain in SPAIN stays mainly in the plain"; var test = "ain"; var res = str.match(new RegExp(test, "gi")); 

This will return:

 Array [ "ain", "AIN", "ain", "ain" ] 

Note:

Form str.match(test, "gi"); only works in the Firefox browser, but is outdated and issues a console warning from Firefox 39 (see RGraham's comment).

+5
source share

All Articles