Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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

Let's say I have the following regular expression:

/hellosworld!/g

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

new RegExp(/hellosworld!/g)

Would it return a regular expression containing /hellosworld!/g, like this:

//hellosworld!/g/

Or would it return the original regular expression?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...