I am Hack Sparrow
Captain of the Internets.

JavaScript – Use Variables with Regular Expressions

How to use variables with 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 flexible? 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 RegExp literal object. But that doesn't mean there is no way to pass variables to a Regular Experssion in JavaScript.

Enter RegExp():

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 for 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"

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

3 Responses to “JavaScript – Use Variables with Regular Expressions”

  1. Angel says:

    This:
    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”

    doesn’t work.

  2. kelvin says:

    how do you replace text with a text file from a text area in javascript? Please send me an email here: buyresearchpaper@yandex.com

  3. Samantha says:

    OMG. This was sooo helpful. Thanks.

    var re = RegExp(‘ool’, ‘gi’);

    I couldn’t figure out how to set re to a variable AND do the global search for the loop in my letter matching script. But now I do!
    Heres part of it:
    var char = new RegExp(word[i], ‘gi’);
    var repeats = (word.match(char));

Make a Comment