JavaScript RegExp lastIndex property

Definition and usage

lastIndex The property specifies the index to start the next match.

Note:This property is only valid when the "g" modifier is set.

This property returns an integer that specifies exec() or test() The position immediately following the last match found by the method.

Note:if exec() and test() If no match is found, then lastIndex is reset to 0.

Example

let text = "The rain in Spain stays mainly in the plain";
let pattern = /ain/g;
let result = "";
while (pattern.test(text)==true) {
  result += "Found at pos " + pattern.lastIndex + "<br>";
}

Try it yourself

Syntax

regexp.lastIndex

Return value

Type Description
Number An integer that specifies the position of the character immediately following the last match found by the exec() or test() methods.

Technical details

The lastIndex property of the RegExp object lastIndex The property is a readable and writable value. For regular expressions that have the g flag set, this property stores an integer that declares the position of the first character after the last matched text.

The result of the last match is found by the methods RegExp.exec() and RegExp.test(), both of which are set to lastIndex The position pointed to by the property is used as the starting point for the next search. This allows you to traverse all matching texts in a string by repeatedly calling these two methods.

This property is readable and writable. It can be set as soon as the next search of the target string begins. lastIndex property is reset to 0.

browser supports

lastIndex Er en ECMAScript1 (ES1) egenskab.

Alle browsere understøtter fuldt ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support