RegExp.lastIndex

Summary

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

Property attributes of RegExp.lastIndex
Writable Yes
Enumerable No
Configurable No

Syntax

lastIndex = regExpObj.lastIndex;

Description

This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:

  • If lastIndex is greater than the length of the string, regexp.test and regexp.exec fail, then lastIndex is set to 0.
  • If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at 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.

Examples

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\" with lastIndex equal to 2.

console.log(re.exec("hi"));
console.log(re.lastIndex);

Returns [\"\"], 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 Status Comment
ECMAScript 3rd Edition. Implemented in JavaScript 1.2. Standard Initial definition.
JavaScript 1.5: lastIndex is a property of a RegExp instance, not the RegExp object.
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

Contributors to this page: Sheppy, fscholz, ethertank, Prodoc, aaco, Mgjbot, Nfroidure, Maian, Dria
Last updated by: aaco,