How to use variables in Regular Expression#

So you know the basics of Regular Expressions in JavaScript and often use it for replacing text etc.

Example:

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.

The concatenator operator doesn't work with the literal regular expression object. But that doesn't mean there is no way to pass variables to a regular experssion in JavaScript.

Enter the RegExp class:

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 g or i or m to the expression?

Just pass them as the second parameter of RegExp().

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:

str.replace(/ool$/, 'ewl');

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.

Run
Clear

There you have it, variables in regular expressions with modifiers and special characters in JavaScript.

References#

  1. Regular Expressions