RegExp lastIndex Property - Javascript RegExp

Javascript examples for RegExp:Property

Description

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

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

Return Value

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

The following code shows how to Do a global search for "ain" in a string, and output the index after a match is found:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<script>
var str = "brain tain pain paint rain in Spain stays mainly in the plain";
var patt1 = /ain/g;/*from   w  ww .ja va  2s .  c om*/

while (patt1.test(str)==true)
{
  document.write("'ain' found. Index now at: "+patt1.lastIndex);
  document.write("<br>");
}
</script>

</body>
</html>

Related Tutorials