1

The right way to assign a RegExp to a variable is by using "new", since it's a constructor, but it also works without it, like in this example:

var a = RegExp('abc');
var b = new RegExp('abc');
console.log(a, b, "abcd".match(a), "abcd".match(b), a == b);

output: /abc/ /abc/ Array["abc"] Array["abc"] false

So my question is - do I need to use "new"?

On the other hand a == b fails, so are they different somehow, because their objects look the same?

2 Answers2

3

They are exactly equivalent. See the specification:

The RegExp constructor:

creates and initializes a new RegExp object when called as a function rather than as a constructor. Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.

That said, using the constructor when not necessary is a bad idea, because it can lead to bugs and hard-to-read code due to backslashes having to be double escaped. When you can, consider using regex literals instead, whose backslashes do not have to be double-escaped.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I do have a more complex regexp that is dynamic, so I can not use literals. On the other hand, examples here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp use "new" even for the simplest case, so that's quite misleading then. –  Nov 10 '20 at 02:23
  • On that link, I see how they're showing how using a regex literal and `new RegExp` can be equivalent, with different syntax, but after the syntax is defined, all of the examples below look to use regex literals (which is good). Are you seeing an unnecessary use of `new` somewhere? – CertainPerformance Nov 10 '20 at 02:25
  • You can equally show how using a regex literal and RegExp can be equivalent, without "new". Why did they provide an example with "new" if it's (1)not necessary, (2)bad idea? Anyway, I'll accept you answer because my question is not about the quality of moz documentation. –  Nov 10 '20 at 02:35
  • It's not that `new` is a bad idea, it's that using the constructor *at all* is a bad idea when not necessary (but sometimes it's necessary, like in your case). I was going to edit the MDN page if I saw a place where it was using the constructor unnecessarily (when not simply describing the syntax), but I don't see any problems with it. – CertainPerformance Nov 10 '20 at 02:38
  • @alikim I saw the unaccept, was there an issue? – CertainPerformance Sep 19 '21 at 03:17
  • There is **no issue** about this special `RegExp`, even in the mentioned reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#syntax ... but about general use, this is a good explain: https://stackoverflow.com/a/1928468/7514010 – MMMahdy-PAPION Jan 11 '22 at 11:12
0

The RegExp constructor also can be used to copy an existing regex,

var r1 = /abc/
var r2 = new RegExp(r1)
York Chen
  • 744
  • 4
  • 9