Differences between Javascript regexp literal and constructor

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.

Leave a Comment