Export (0) Print
Expand All

lastIndex Property

Returns the character position where the next match begins in a searched string.

{RegExp | reArray}.lastIndex

RegExp

Required. The global RegExp object.

reArray

Required. An array returned by the exec method of a Regular Expression object.

The lastIndex property is zero-based, that is, the index of the first character is zero. Its initial value is –1. Its value is modified whenever a successful match is made.

The lastIndex property of the RegExp object is modified by the exec and test methods of the RegExp object, and the match, replace, and split methods of the String object.

The following rules apply to values of lastIndex:

  • If there is no match, lastIndex is set to -1.

  • If lastIndex is greater than the length of the string, test and exec fail and lastIndex is set to -1.

  • If lastIndex is equal to the length of the string, the regular expression matches if the pattern matches the empty string. Otherwise, the match fails and lastIndex is reset to -1.

  • Otherwise, lastIndex is set to the next position following the most recent match.

The initial value of the RegExp.lastIndex property is –1. Its value is read-only and changes whenever a successful match is made.

NoteNote

The properties of the RegExp object are not available when running in fast mode, the default for JScript. To compile a program from the command line that uses these properties, you must turn off the fast option by using /fast-. It is not safe to turn off the fast option in ASP.NET because of threading issues.

The following example illustrates the use of the lastIndex property. This function iterates a search string and prints out the index and lastIndex values for each word in the string.

var src : String = "The quick brown fox jumps over the lazy dog.";
var re : RegExp = /\w+/g;
var arr : Array;
while ((arr = re.exec(src)) != null)
{
    print(arr.index + "-" + arr.lastIndex + "\t" + arr[0]);
}

The output of this program is:

0-3     The
4-9     quick
10-15   brown
16-19   fox
20-25   jumps
26-30   over
31-34   the
35-39   lazy
40-43   dog

Community Additions

ADD
Show:
© 2014 Microsoft