56

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

new RegExp("[abc]")

And

/[abc]/

And if with modifiers then what is the use of additional backslash (\)

/\[abc]/g

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 find an explanation of which is best and what the difference is.

4
  • 2
    Note that /\[abc]/g will match [abc] because first bracket is escaped. This is completely different from new RegExp("[abc]") and /[abc]/. Commented Apr 28, 2016 at 10:38
  • 1
    yeah i know /\[abc]/g i mentioned this to know why we need to use extra ` \ ` if we are using modifiers Commented Apr 28, 2016 at 10:40
  • 5
    No, there is no need. You can add modifiers after last / e.g. /[abc]/gi Commented Apr 28, 2016 at 10:41
  • 6
    Note also that the new in new RegExp is extraneous and you may as well omit it. There is no noticeable performance benefit to using new. Commented May 30, 2017 at 19:32

4 Answers 4

78
+50

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But please note that the literal syntax is compliled only once, with the JS code, while the new Regexp() form must compile the regular expression each time it is called - so performance will be better with the literal version: Use it whenever possible!
Sure, but here a literal is not possible as it's not dynamic (at least without using eval().)
I was having trouble with a particular regular expression until I saw this answer saying: "because the pattern is specified as a string". The key part is the word string because any escape sequence that you put in a string needs to be escaped to appear in the regular expression pattern, otherwise they'll be replaced by their literal characters, e.g. /\n/ will become new RegExp( '\\n' ) and the same goes for backreferences, /(...)\1/ becomes new RegExp('(...)\\1'). In summary and to complement this answer: escape all backslashes
Actually you can give the constructer a literal as well. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
12
  1. As you can see, the RegExp constructor syntax requires string to be passed. \ in the string is used to escape the following character. Thus,

    new RegExp("\s") // This gives the regex `/s/` since s is escaped.
    

    will produce the regex s.

    Note: to add modifiers/flags, pass the flags as second parameter to the constructor function.

    While, /\s/ - the literal syntax, will produce the regex which is predictable.

  2. The RegExp constructor syntax allows to create regular expression from the dynamically.

So, when the regex need to be crafted dynamically, use RegExp constructor syntax otherwise use regex literal syntax.

Comments

3

They are kind of the same but "Regular expression literals should be used when possible" because it is easier to read and does not require escaping like a string literal does.

Escaping example:

new RegExp("\\d+");

Regular expression literals (recommended):

/\d+/;

Using the RegExp constructor is suitable when the pattern is computed dynamically, e.g. when it is provided by the user.

Source SonarLint Rule.

Comments

0

There are 2 ways of defining regular expressions.

  1. Through an object constructor
    • Can be changed at runtime.
  2. Through a literal.
    • Compiled at load of the script
    • Better performance

The literal is the best to use with known regular expressions, while the constructor is better for dynamically constructed regular expressions such as those from user input.

You could use any of the two and they will be handled in exactly the same way..

5 Comments

"Through a literal" section is incorrect - those are just myths which are, unfortunately, extremely popular. JS engines don't do any distinctions on execution level between those. No matter how RegExp creation was written in the code (whether via syntax sugar or global constructor), emitted code is just the same and regexp is compiled lazily on its first use.
@RReverser - MDN says otherwise, though I accept that the docs might not have been written by the coders. developer.mozilla.org/en/docs/Web/JavaScript/Guide/…
@RReverser, do you have documentation to support what you're claiming? Have a look at ecma-international.org/ecma-262/6.0/#sec-regexp-pattern-flags. Using a literal does indeed shortcut the algorithm by no trivial number of steps. Although the difference in the perceived speed to carry out such a computation is trivial by today's standards, it is indeed less performant to use a string in the constructor rather than a literal. Now, "Compiled at load of the script" does sound like it may be false.
@papiro Please don't treat a spec as an actual implementation - it's meant only as a reference for externally observable behaviour and doesn't provide insights into what engines are actually doing. The easiest way to re-check any performance claims is by measuring, which you can easily do.
@mwardm Sorry missed your message earlier. MDN might be simply outdated, as old engines would indeed lack many of modern optimisations. Luckily, MDN is just a wiki and easy to update by anyone willing to do so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.