JavaScript: RegExp constructor vs RegEx literal

The key difference is that literal REGEX can’t accept dynamic input, i.e. from variables, whereas the constructor can, because the pattern is specified as a string.

Say you wanted to match one or more words from an array in a string:

var words = ['foo', 'bar', 'orange', 'platypus'];
var str = "I say, foo, what a lovely platypus!";
str.match(new RegExp('\\b('+words.join('|')+')\\b', 'g')); //["foo", "platypus"]

This would not be possible with a literal /pattern/, as anything between the two forward slashes is interpreted literally; we’d have to specify the allowed words in the pattern itself, rather than reading them in from a dynamic source (the array).

Note also the need to double-escape (i.e. \\) special characters when specifying patterns in this way, because we’re doing so in a string – the first backslash must be escaped by the second so one of them makes it into the pattern. If there were only one, it would be interpreted by JS’s string parser as an escaping character, and removed.

Leave a Comment