The lastIndex is a read/write integer property of regular expression instances that specifies the index at which to start the next match.

Property attributes of RegExpInstance.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:

  • If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.
  • If lastIndex is 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 from lastIndex.
  • If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
  • Otherwise, lastIndex is set to the next position following the most recent match.


Using lastIndex

Consider the following sequence of statements:

var re = /(hi)?/g;

Matches the empty string.


Returns ["hi", "hi"] with lastIndex equal to 2.


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.


ECMAScript (ECMA-262)
The definition of 'RegExp.lastIndex' in that specification.

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
lastIndexChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes


Full support  
Full support

See also