The regular expression object in JavaScript has the test() and exec() methods for regular expression problems. This object is called RegExp. The JavaScript String object has the match(), search(), replace() and split() methods for regular expression problems. The string object methods are actually better and easier to apply than the RegExp object methods. This two-part series takes a look at what you can do with them.
JavaScript String Regular Expressions - Knowing Where Matching Occurs in the Available String (Page 3 of 5 )
The lastIndex property of RexExp
The RegExp object has what is called the lastIndex property. This property gives you the index where the next search will start in the available string. This property can only be used when the global flag is set for the RegExp object. You can use either the test() or exec() methods. The following code illustrates this:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var availableString = "We have a dog in our compound.";
var re = /dog/g;
re.exec(availableString);
alert(re.lastIndex);
</script>
</body>
</html>
The first statement in the script declares the variable for the available string. The next statement declares the RegExp object, re. Note the global flag. The statement after that executes the exec() method of the re (RexExp) object. The exec() or test() method is always executed with a RegExp object.
When any of them is executed, and with the global flag set, the RexExp object, in this case re, sets its lastIndex property to the value where the next search should start in the available string. Now index counting in a JavaScript string begins from zero. So the lastIndex in this example is 13, the next character is a whitespace character after "dog." In the above code the “alert(re.lastIndex)” expression should display 13.
The equivalent for this lastIndex property does not exist for any string method. However, with the string method search(), you can get an index which you can call the firstIndex.