JS: Regex Flag y (sticky)

By Xah Lee. Date: . Last updated: .

Flag y (sticky)

(new in ECMAScript 2015)

when on, the beginning position of the match must be the same as RegExp.prototype.lastIndex.

/* demo of regex flag y.
show that the beginning position of the match must be the same as lastIndex. */

const rgx = /i/y;
console.assert(rgx.lastIndex === 0);
console.assert(rgx.exec("big") === null);

// no match because lastIndex is 0, the i occur at index 1.

// set to 1
rgx.lastIndex = 1;

// now matches
console.log(rgx.exec("big"));
// [ "i", index: 1, input: "big", groups: undefined ]
/* demo of set sticky flag y in regex */

const xtext = "dog dog";

// set sticky flag in regex
const rgx = /d/y;

// lastIndex is 0 by default
console.assert(rgx.lastIndex === 0);

const xresult1 = rgx.exec(xtext);
// [ "d", index: 0, input: "dog dog", groups: undefined ]

// matched d
console.assert(xresult1[0] === "d");

// at index 0
console.assert(xresult1.index === 0);

// lastIndex is advanced to end of match
console.assert(rgx.lastIndex === 1);

// no match because the d does not happen on lastIndex 1
console.assert(rgx.exec(xtext) === null);

RegExp.prototype.sticky

property RegExp.prototype.sticky value is true if flag y is set.

const rgx = /some/y;
console.assert(rgx.sticky === true);

Regex functions and Regex Flag y

in JavaScript, what regex function does Regex Flag y (sticky) has effect

(ai answer)

Primarily RegExp.prototype.exec() (and test(), which wraps it).

The sticky (y) flag forces the match to start exactly at the regex’s lastIndex. It does not scan forward like the global (g) flag.

Behavior summary (from MDN)

Example:

const re = /foo/y;
const str = "barfoo";
re.lastIndex = 3;
console.log(re.exec(str)); // ["foo", index: 3, ...]
console.log(re.lastIndex); // 6

re.lastIndex = 0;
console.log(re.exec(str)); // null (no match at 0), lastIndex reset to 0

Use y mainly when you need strict position-based matching (e.g. tokenizers/parsers) with exec/test in a loop.