RegExp.prototype.lastIndex
The index at which the next match will start for global or sticky regexes.
Syntax
regexp.lastIndex
Returns
number — The position where the next search begins.
Examples
const re = /a/g;
re.exec("xaxa");
console.log(re.lastIndex);
Output
2
const re = /a/g;
console.log(re.test("aaa"));
re.lastIndex = 0;
console.log(re.test("aaa"));
Output
true
true
Notes
- Only consulted and updated when the `g` or `y` flag is set.
- Reset it to `0` to restart, or reuse a non-global regex to avoid
stateful surprises.
- A no-match resets `lastIndex` to `0`.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |