Gaurav Aggarwal Gaurav Aggarwal - 5 months ago 36x
Javascript Question

JavaScript: RegExp constructor vs RegEx literal

I am studying about RegExp but everywhere I can see two syntax

new RegExp("[abc]")



And if with modifiers then what is the use of additional slash (


I am not getting any bug with these two but I wonder is there any difference between these two. If yes then what is it and which is best to use?

I referred Differences between Javascript regexp literal and constructor but there I didn't found explanation of which is best and what is difference.


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 a number of words, which came from an array:

var words = ['foo', 'bar', 'orange', 'platypus'];
var str = "Foo something nice orange what a lovely platypus";
str.match(new RegExp('\\b('+words.join('|')+')\\b'));

This would not be possible with a literal /pattern/.