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.