JS: RegExp.prototype.lastIndex

By Xah Lee. Date: . Last updated: .
RegExp.prototype.lastIndex
  • A index for the target string, for regex function to begin match.
  • It is automatically set by regex functions, usually when regex flag g is on, to allow you to do a loop to find all occurrences.
  • When regex flag g is off, this value is 0.
  • When it is on, the regex function, when finished execution, advanced the index by set the index to end position of a match (or 0 when no more match), so next call will start search from there.
// Repeated call with regex flag g.

const xtext = "012x45x78x";
const xre = /x/g;

console.log(xre.lastIndex);
// 0

console.log(xre.test(xtext));
// true

console.log(xre.lastIndex);
// 4

console.log(xre.test(xtext));
// true

console.log(xre.lastIndex);
// 7

Regex functions that use this flag: