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.
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);
}
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With