Description: The next match of the regular starting position for the lastIndex property provisions.
Note: This property is only set to use the g flag.
Results are matched by the process of the last RegExp.exec () and RegExp.test () found, they are referred to the position as a starting point lastIndex property next retrieval. Thus, by repeatedly call these two methods through which all matches a text string.
Note: This property is readable and writable. As long as the next target string of beginning a search, you can set it up. When the method exec () or test () could not find a match text, they will automatically reset to 0 lastIndex property.
Example 1: Try the global string substring "ain", and outputs the match after the completion of the lastIndex property:
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>"); };
Example 2: repeatedly retrieve and print out the lastIndex position, when finally retrieved not retrieved it from scratch in line with the retrieval
var str="The rain in Spain stays"; var patt=/ain/g; console.log(patt.test(str))//true console.log(patt.lastIndex)//8 console.log(patt.test(str))//true console.log(patt.lastIndex)//17 console.log(patt.test(str))//false console.log(patt.lastIndex)//0 console.log(patt.test(str))//true console.log(patt.lastIndex)//8
Example 3: How to avoid caused due lastIndex bug: always create a new RegExp can avoid this problem
var str="The rain in Spain stays"; console.log(/ain/g.test(str))//true console.log(/ain/g.lastIndex)//0 console.log(/ain/g.test(str))//true console.log(/ain/g.lastIndex)//0 console.log(/ain/g.test(str))//false console.log(/ain/g.lastIndex)//0 console.log(/ain/g.test(str))//true console.log(/ain/g.lastIndex)//0