Differences between literal and regexp Javascript constructor

We recently got an error when another developer changed the RegExp literal to a constructor call, and I was wondering why there is any difference at all. The exact code was

var parts = new RegExp("/rt:([^@]+)@(\d+)/").exec(tag); 

compared to the original

 var parts = /rt:([^@]+)@(\d+)/.exec(tag); 

When a tag , for example rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077 , the first (buggy) call returns null and the second returns ["rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077", "60C1C036-42FA-4073-B10B-1969BD2358FB", "00000000077"]

Needless to say, I brought the changes back, but I would like to know why there is such a difference.

+16
javascript regex
Nov 01 2018-11-11T00:
source share
2 answers

There are two problems:

/ not part of the expression. They are delimiters denoting a regular expression literal. They need to be removed if you use RegExp , otherwise they will literally match the slash.

Secondly, the backslash is an escape character in string literals. To create a literal \ for an expression, you need to escape it in a string.

So the equivalent would be:

 new RegExp("rt:([^@]+)@(\\d+)") 



In particular, escaping makes an expression more difficult to write if you want to use RegExp . This is really only necessary if you want to dynamically create an expression, that is, if you want, for example, to include text stored in a variable. If you have a fixed expression, the literal /.../ easier to write and more concise.

+31
Nov 01 '11 at 10:09
source share

\d must be escaped when passed to the new RegExp constructor. So it should be

 var parts = new RegExp("rt:([^@]+)@(\\d+)").exec(tag); 
+4
Nov 01 '11 at 10:09
source share



All Articles