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.
The RegExp constructor creates a regular expression object for matching text with a pattern. For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .
The expression new RegExp(/ab+c/, flags) will create a new RegExp using the source of the first parameter and the flags provided by the second. When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With