Scanning successive matches
Iterate through every match while retaining capture groups and each match's position.
JS Puzzles · Const
RegExp.lastIndex records where the next search starts for global and sticky regular expressions. Successful matches advance it, while failed exec() calls reset it to 0; assigning it manually selects a starting offset.
A global or sticky RegExp stores the position used for its next search in lastIndex. A successful exec() or test() advances it to the end of the match; a failed search resets it to 0, and you can assign a starting position yourself.
regexp.lastIndexconst re = /\w+/g;
const text = "one two";
console.log(re.exec(text)[0]); // "one"
console.log(re.lastIndex); // 3
console.log(re.exec(text)[0]); // "two"
console.log(re.lastIndex); // 7
re.lastIndex = 0;
console.log(re.exec(text)[0]); // "one"A global regular expression resumes each exec() call at lastIndex; assigning 0 starts over.
Iterate through every match while retaining capture groups and each match's position.
Start a global search at a known character offset.
Parse input sequentially, requiring each token to begin exactly where the previous one ended.
lastIndex is the position from which the next match begins for a global or sticky regular expression. After a successful exec(), it becomes the position immediately after the matched text; after failure, it resets to 0.
Follow-up: What happens when lastIndex is beyond the input length? exec() finds no match and resets lastIndex to 0.
With g, the engine starts at lastIndex but may continue at later positions if the pattern does not match there. With y, matching must occur exactly at lastIndex, so it is useful for position-sensitive tokenization.
Follow-up: How would you make a sticky regex parse from a chosen offset? Assign that offset to lastIndex before calling exec() or test().
A global regex retains its position between calls, so repeated exec() calls can iterate through successive matches. The same stateful behavior applies to test(), which also advances lastIndex.
Follow-up: How can a reused regex avoid stale state? Set lastIndex to 0 before the new search, or use suitable string methods that do not use the regex's saved position.
RegExp.prototype.exec()RegExp.prototype.test()RegExp.prototype.stickyString.prototype.match()String.prototype.search()