Global in Regex - State

Published on April 12, 2021

โ† Back to tips

Did you know that the global flag in regular expression has itโ€™s own state?

Yes, after an expression test, it stores the index of the evaluated string, and continues from that index for further evaluations.

Here is what I mean ๐Ÿ”ฝ

Iโ€™m trying to test a string with a simple regex.

Although, at first thought, it might seem like the expression would pass all the time, the second evaluation fails.

Global Regex Example

This is because, during the second evaluation, regex tests only the substring โ€ bar bazโ€ as the previous test would have evaluated the first 3 characters.

๐ŸŽ‰ Interested in Frontend or Indie-hacking?

I talk about the latest in frontend, along with my experience in building various (Indie) side-projects