-
Versionv16.13.2 PlatformDarwin Romans-MBP.zyxel.box 22.3.0 Darwin Kernel Version 22.3.0: Thu Jan 5 20:49:43 PST 2023; root:xnu-8792.81.2~2/RELEASE_ARM64_T8103 arm64 SubsystemNo response What steps will reproduce the bug?
node
> /\/teams(?:\/)?/g.test('/teams')
true
> /\/teams(?:\/)?/g.test('/teams/')
true
> const re = /\/teams(?:\/)?/g;
undefined
> re.test('/teams')
true
> re.test('/teams/')
false How often does it reproduce? Is there a required condition?Always. What is the expected behavior?Same result regardless whether the regular expression is stored in a variable or not. What do you see instead?Different results. Additional informationI was also able to reproduce it in Brave console (Version 1.48.158 Chromium: 110.0.5481.77 (Official Build) (arm64)). |
Beta Was this translation helpful? Give feedback.
Replies: 0 comments 1 reply
-
I've converted this to a discussion because it's not a bug. The You can read more here: https://javascript.plainenglish.io/most-surprising-behavior-of-javascript-regular-expression-you-have-ever-seen-1ddb84539163 |
Beta Was this translation helpful? Give feedback.
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 theg
flag becomes relevant.You can read more here: https://javascript.plainenglish.io/most-surprising-behavior-of-javascript-regular-expression-you-have-ever-seen-1ddb84539163