How to use variables in Regular Expression#
var sentence = 'Regular Expression'; sentence.replace(/ssion/, 'shun'); // "Regular Expreshun"
Now what if the string you need to replace needs to be dynamic? Well you could use a variable!
var replacee = 'sion'; var replacer = 'hun'; sentence.replace(/+ replacee +/, replacer); // SyntaxError: invalid quantifier
Oops! That didn't work out at all.
var re = new RegExp(replacee); sentence.replace(re, replacer); // "Regular Expreshun"
Yay! So it looks like we can very well use variables with Regular Expressions. Now what if you need to pass a modifier like
m to the expression?
Just pass them as the second parameter of
var str = 'I am cool man in a COOL skool'; var re = RegExp('ool', 'gi'); str.replace(re, 'ewl'); // "I am cewl man in a Cewl skewl"
And now a slightly different scenario. How do you use special Regular Expression characters with
RegExp()? For example you want to do something like this:
Just escape the characters that have special meaning in Regular Expressions:
var str = 'I am cool man in a COOL skool'; var re = RegExp('ool\$', 'gi'); str.replace(re, 'ewl'); // "I am cool man in a COOL skewl"
Confirm it actually works in this executable example.