RegExp: lastIndex
lastIndex is a read/write integer property of RegExp instances that specifies the index at which to start the next match.
Note that lastIndex is not a property of the RegExp prototype but is instead only exposed from RegExp instances.
Property attributes of RegExp: lastIndex |
|
|---|---|
| Writable | yes |
| Enumerable | no |
| Configurable | no |
Description
This property is set only if the regular expression instance used the g flag to indicate a global search, or the y flag to indicate a sticky search. The following rules apply:
- If
lastIndexis greater than the length of the string,test()andexec()fail, thenlastIndexis set to 0. - If
lastIndexis equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting fromlastIndex. - If
lastIndexis equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, andlastIndexis reset to 0. - Otherwise,
lastIndexis set to the next position following the most recent match.
Examples
Using lastIndex
Consider the following sequence of statements:
var re = /(hi)?/g;
Matches the empty string.
console.log(re.exec('hi'));
console.log(re.lastIndex);
Returns ["hi", "hi"] with lastIndex equal to 2.
console.log(re.exec('hi'));
console.log(re.lastIndex);
Returns ["", undefined], an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex was 2 (and still is 2) and hi has length 2.
Specifications
| Specification |
|---|
| ECMAScript Language Specification (ECMAScript) # sec-properties-of-regexp-instances |
Browser compatibility
BCD tables only load in the browser