Skip to content

Regular expression produces different results depending whether it's stored in a variable or not #5043

Answered by cjihrig
romfrolov asked this question in Q&A
Discussion options

You must be logged in to vote

I've converted this to a discussion because it's not a bug. The g flag on the regular expression maintains state. When you use a regular expression literal, you are creating a new regular expression each time. When you assign it to a variable, you are reusing the same regular expression object, so the state of the g flag becomes relevant.

You can read more here: https://javascript.plainenglish.io/most-surprising-behavior-of-javascript-regular-expression-you-have-ever-seen-1ddb84539163

Replies: 0 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by Trott
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants