Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: String.match() - pass string variable in regular expression [duplicate]

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

The problem is to make a variable string to become part of the regular expression.

Tutorial Sample code:

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 work.

like image 466
Mohitt Avatar asked Jun 25 '15 06:06

Mohitt


2 Answers

Use the regex constructor, like:

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);
}
like image 124
CD.. Avatar answered Oct 21 '22 19:10

CD..


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

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

If your variable contains special chars, it's better to escape those.

var re = new RegExp(test.replace(/(\W)/g, "\\$1"), "gi");
like image 8
Avinash Raj Avatar answered Oct 21 '22 18:10

Avinash Raj