In JavaScript, regex.lastIndex is a writable number. It is the index where the next search starts for a global (g) or sticky (y) RegExp.
After a successful exec() or test(), the engine updates lastIndex. If you reuse the same regex, reset it with regex.lastIndex = 0 when you want to start over.
Syntax
Read or set lastIndex on a global or sticky regex.
JavaScript
const re = /\d+/g;
const text = "a1 b2";
console.log(re.exec(text)[0]); // "1"
console.log(re.lastIndex); // 2
console.log(re.exec(text)[0]); // "2"
re.lastIndex = 0; // start over
Call
What it does
regex.lastIndex
Read the next search index (number).
regex.lastIndex = 0
Restart searching from the beginning.
regex.exec(str)
With g or y, updates lastIndex after each call.
Remember this at a glance:
Remember
/\d+/g.lastIndex → 0 at first
with g or y:
each exec()/test() may change lastIndex
reset: regex.lastIndex = 0
without g/y:
lastIndex is usually ignored by exec/test
What You Get
Name
Description
regex.lastIndex
Writable integer. Next search index for g or y regexes.
Default
Starts at 0 on a new RegExp.
After failure
Often reset to 0 when a search finds no more matches.
Value
Value
Description
Number ≥ 0
Index in the string where the next g/y search begins.
JavaScript Examples
Example 1 — Watch lastIndex change
Call exec twice on a global regex.
JavaScript
const re = /\d+/g;
const text = "x12y34";
console.log(re.exec(text)[0]);
console.log(re.lastIndex);
console.log(re.exec(text)[0]);
console.log(re.lastIndex);
Resetting to 0 makes the third test succeed again.
Example 3 — Loop all matches
Use exec until it returns null.
JavaScript
const re = /\w+/g;
const text = "one two three";
let m;
const words = [];
while ((m = re.exec(text)) !== null) {
words.push(m[0]);
}
console.log(words.join(", "));
console.log(re.lastIndex);