Core JavaScript 1.5 Reference:Global Objects:RegExp:lastIndex
From MDC
[edit] Summary
A read/write integer property that specifies the index at which to start the next match.
| Property of RegExp | |
| Implemented in: | JavaScript 1.2, NES3.0
JavaScript 1.5: |
| ECMA Version: | ECMA-262, Edition 3 |
[edit] Description
lastIndex is a property of an individual regular expression object.
This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:
- If
lastIndexis greater than the length of the string,regexp.testandregexp.execfail, andlastIndexis set to 0.
- If
lastIndexis equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting atlastIndex.
- If
lastIndexis equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, andlastIndexis reset to 0.
- Otherwise,
lastIndexis set to the next position following the most recent match.
For example, consider the following sequence of statements:
-
re = /(hi)?/g - Matches the empty string.
-
re("hi") - Returns
["hi", "hi"]withlastIndexequal to 2.
-
re("hi") - Returns
[""], an empty array whose zeroth element is the match string. In this case, the empty string becauselastIndexwas 2 (and still is 2) and "hi" has length 2.