Course contentsShow
← JavaScript
Lesson 1739 of 2,72336. Regular ExpressionsFree lesson

Global Flag and lastIndex Statefulness

How the g flag makes regex objects stateful, causing unexpected behavior in repeated exec calls.

Global Flag and lastIndex Statefulness

What you'll learn: How the g flag makes regex objects stateful, causing unexpected behavior in repeated exec() calls.

The Hidden Trap of Global Regexes

When you use the global flag (g) with a regex literal or constructor, that regex object becomes stateful. It maintains an internal property called lastIndex that tracks where the next search should begin. This is useful for iterating through multiple matches, but it can cause surprising bugs if you're not aware of it.

Each time you call exec() on a global regex and it finds a match, it updates lastIndex to the position after that match. The next exec() call starts searching from lastIndex, not from the beginning. When no match is found, lastIndex resets to 0.

The Problem in Action

const regex = /\d+/g;

console.log(regex.exec("I have 3 cats")); // ["3", ...]
console.log(regex.lastIndex);             // 9

console.log(regex.exec("I have 3 cats")); // null (starts at index 9)
console.log(regex.lastIndex);             // 0 (reset)

console.log(regex.exec("I have 3 cats")); // ["3", ...] (starts over)

Notice how the second exec() returns null because it continues from where it left off—there's nothing to match after index 9. This can break code that reuses the same regex against different strings or expects fresh results each time.

The Solution

You can manually reset lastIndex between searches, or avoid reusing global regex objects:

regex.lastIndex = 0; // Manual reset

Or create a new regex each time you need a fresh search.

Key Takeaway: Global regexes are stateful—they remember their position via lastIndex. Always reset lastIndex or create new regex instances when reusing global patterns across multiple searches.