JavaScript lastIndexProperty

RegExp 对象 参考手册JavaScript RegExp Object

Definition and Usage

The lastIndex property is used to specify the starting position for the next match.

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

The results of the last match are 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, you can traverse all matching text in a string by repeatedly calling these two methods.

Note:This property is readable and writable. It can be set as long as the next search of the target string begins. When the method 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

In the string, globally try the substring "ain" and output the lastIndex property after the match is completed:

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("<br>"); }

Try it Yourself »


RegExp 对象 参考手册JavaScript RegExp Object Other Extensions