JavaScript Regex Flags, lastIndex and Stateful Matching
Quick answer
Flags modify regex behavior. The global and sticky flags make repeated matching operations depend on the mutable lastIndex property.
How it works
g searches from lastIndex; y requires matching exactly there. A successful built-in exec with g or y updates lastIndex to the end of the match; failure resets it to zero. i ignores case, m extends input anchors to line boundaries, s includes line terminators in dot, d exposes indices, u and v enable Unicode-aware modes. u and v cannot be combined. With empty matches, repeated raw exec may not advance.
const re = /a/g;console.log(re.test("a"), re.lastIndex);console.log(re.test("a"), re.lastIndex);Expected output in Node.js:
true 1false 0The second search starts at the previous end and fails, resetting state.
const re = /b/y; re.lastIndex = 1;console.log(re.test("ab"), re.lastIndex, /a.b/s.test("a\nb"));Expected output in Node.js:
true 2 trueSticky matches at index 1; dotAll allows a newline.
Common mistakes
Do not reuse a global test regex across independent validation calls unless you intentionally reset its state.
Practice
Trace two successful and one unsuccessful global search, writing down lastIndex after each.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Flags, lastIndex and Stateful Matching — Knowledge Check
Apply the taught concept and predict the output.
Which flag requires the next match to start exactly at lastIndex?
What happens to lastIndex after a failed built-in exec with g?
Which flag exposes match index ranges in exec results?
What is the exact console output in JavaScript Regex Flags, lastIndex and Stateful Matching example 1?
const re = /a/g;console.log(re.test("a"), re.lastIndex);console.log(re.test("a"), re.lastIndex);What is the exact console output in JavaScript Regex Flags, lastIndex and Stateful Matching example 2?
const re = /b/y; re.lastIndex = 1;console.log(re.test("ab"), re.lastIndex, /a.b/s.test("a\nb"));