Differences between Javascript regexp literal and constructor

We recently had a bug, after a fellow developer changed a RegExp literal into 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);

vs the original of

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

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

Needless to say, I reverted the change, but I'd like to know why is there such a difference in the first place.


There are two problems:

The / are not part of the expression. They are delimiters, marking a regex literal. They have to be removed if you use RegExp, otherwise they match a slash literally.

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

Thus, the equivalent would be:

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

Especially the escaping makes expression a bit more difficult to write if you want to use RegExp. It is actually only needed if you want to create expression dynamically, that is, if you want to include text stored in a variable for example. If you have a fixed expression, a literal /.../ is easier to write and more concise.


\d needs to be escaped when passesd to new RegExp constructor. So, it needs to be

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