Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript lastIndex Property

JavaScript lastIndex Property

RegExp Object Reference JavaScript RegExp Object


Definition and Usage

The lastIndex property specifies the starting position for the next match.

Note: This property can only be used when the flag g is set.

The result of the last match is found by the methods RegExp.exec() and RegExp.test(), both of which use the position indicated by the lastIndex property as the starting point for the next search. In this way, all matching text in a string can be traversed by repeatedly calling these two methods.

**Note:** This property is readable and writable. It can be set as soon as the next search of the target string begins. When the methods exec() or test() can no longer find matching text, they automatically reset the lastIndex property to 0.

Syntax

RegExpObject.lastIndex


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the lastIndex property.


Example

Example

Globally test the substring "ain" in a string, and output the lastIndex property after matching completes:

var

str

=

"

The rain in Spain stays mainly in the plain

"

;

var

patt1

=/

ain

/

g

;

while

(

patt1

.

test

(

str

)

==

true

)

{

document

.

write

(

"

'ain' found. Index now at:

"

patt1

.

lastIndex

)

;

document

.

write

(

"


"

)

;

}

Try it »


RegExp Object Reference JavaScript RegExp Object