Malekai
Malekai

Reputation: 5011

What happens if you pass a regular expression to the "RegExp" constructor?

Let's say I have the following regular expression:

/hello\sworld\!/g

If I pass this regular expression to the RegExp constructor, without quotation marks:

new RegExp(/hello\sworld\!/g)

Would it return a regular expression containing /hello\sworld\!/g, like this:

/\/hello\sworld\!\/\g/

Or would it return the original regular expression?

Upvotes: 2

Views: 580

Answers (1)

Malekai
Malekai

Reputation: 5011

According to MDN, the following expressions create the same regular expression:

new RegExp("ab+c", "i");
new RegExp(/ab+c/, "i");

Expected result:

/ab+c/i

The result will also be the same if you pass a regex literal with a flag but don't define new flags in the second argument, for example:

new RegExp(/ab+c/i)

Should return the same regex literal (/ab+c/i), but if you do specify new regex flags (in the second argument) all existing flags will be removed.

new RegExp(/ab+c/i, "")
new RegExp(/ab+c/i, "g")
new RegExp(/ab+c/i, "m")

Expected result:

/ab+c/
/ab+c/g
/ab+c/m

What does the literal notation do?

The literal notation provides a compilation of the regular expression when the expression is evaluated.

When should I use the literal notation?

Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

What does the constructor function do?

The constructor of the regular expression object (for example, new RegExp('ab+c')) provides runtime compilation of the regular expression.

When should I use the constructor function?

Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Good luck.

Upvotes: 3

Related Questions