JS: regex flag y (sticky)

By Xah Lee. Date: .

Flag y (sticky)

(new in ECMAScript 2015)

Make the match start at the index RegExp.prototype.lastIndex RegExp.prototype.lastIndex. (does not change the meaning of ^. It still mean beginning of string or line.)

const rgx = /bat/y;
console.log(rgx.exec("batman"));
// [ "bat", index: 0, input: "batman", groups: undefined ]
console.log(rgx.lastIndex);
// 3

// Next match must start at index 3
console.log(rgx.exec("batman"));
// null
console.log(rgx.lastIndex);
// 0

// Reset and try again
rgx.lastIndex = 0;
console.log(rgx.exec("bat bat"));
// [ "bat", index: 0, input: "bat bat", groups: undefined ]
console.log(rgx.lastIndex);
// 3

rgx.lastIndex = 4;
console.log(rgx.exec("bat bat"));
// [ "bat", index: 4, input: "bat bat", groups: undefined ]