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

Sticky Mode with 'y'

How the 'y' flag enforces matching at the exact lastIndex position without searching ahead.

Sticky Mode with 'y'

You'll learn how the y flag forces a regex to match only at the exact lastIndex position, without searching ahead through the string.

What Makes It "Sticky"

Most regex patterns with the global flag (g) will search through a string from lastIndex onward, skipping characters until they find a match. The sticky flag (y) is different: it insists on a match starting precisely at lastIndex. If the pattern doesn't match at that exact spot, the search fails immediately—no hunting ahead allowed.

Think of g as a detective who searches room by room until finding evidence, while y is a guard checking the exact spot you told them to watch. If nothing's there, they don't look anywhere else.

How It Works

When you use the y flag, the regex becomes anchored to lastIndex. After each successful match, lastIndex advances to the character immediately after the match. If the next attempt doesn't match right there, the regex fails:

const pattern = /\d+/y;
const text = "12 34 56";

pattern.lastIndex = 0;  // Start at position 0
console.log(pattern.exec(text));  // ["12"] - matches at 0
console.log(pattern.lastIndex);   // 2

console.log(pattern.exec(text));  // null - position 2 is a space, not a digit
console.log(pattern.lastIndex);   // 0 (reset on failure)

Sticky mode is perfect for tokenizers and parsers where you need to consume input sequentially without skipping characters.

Key Differences from Global

With g, the regex would skip the space and find "34". With y, it refuses to skip anything—it's match-here-or-fail.

Key Takeaway: The y flag enforces matching at the exact lastIndex position, making regex "sticky" to that spot without searching ahead—ideal for sequential parsing tasks.