JavaScript lastIndex Property


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 »

Description

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

Note: This property only works if the "g" modifier is set.

This property returns an integer that specifies the character position immediately after the last match found by exec( ) or test( ) methods.

Note: exec( ) and test( ) reset lastIndex to 0 if they do not get a match.

Browser Support

lastIndex is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Syntax

RegExpObject.lastIndex

Return Value

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

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.