26

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.

2 Answers 2

43

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.

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

4 Comments

Good answer, think I'll delete mine! What if you need to reuse a particular RegExp - is that not a good time to use a constructor? Or would you just say var resuasableRegex = /..pattern../; ?
@ElRonnoco: Exactly, you can assign a regex literal to a variable as well.
Thanks for the info. Next time I'll look into the strings better, to make sure there are no escape characters needed. Anyway, literal is much easier for sure.
For small regex, literals are definitely the way to go. If you have a dynamic expression or a very long regex to maintain, RegExp is a nice option. Escaping isn't too bad: just "double the [literal] backslashes and escape the quotes" Javascript - The Good Parts, p. 71. Here's code that will get just the quotes: function escape(text) { return text.replace(/['"]/g, "\\$&"); };
4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.