JS: RegExp.prototype.lastIndex
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
gis on, to allow you to do a loop to find all occurrences. - When regex flag
gis 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: