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.
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 |
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 when test()
and exec()
are called on a given input:
lastIndex
is greater than the length of the input, exec()
or test()
will not find a match, and lastIndex
will be set to 0.lastIndex
is equal to or less than the length of the input, exec()
or test()
will attempt to match the input starting from lastIndex
. exec()
or test()
find a match, then lastIndex
will be set to the position of the end of the matched string in the input.exec()
or test()
do not find a match, then lastIndex
will be set to 0.Consider the following sequence of statements:
const 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.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
lastIndex |
1 |
12 |
1 |
5.5 |
5 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex