{{JSRef("Global_Objects", "RegExp")}}
Summary
The lastIndex
is a read/write integer property of regular expressions that specifies the index at which to start the next match.
{{js_property_attributes(1, 0, 0)}}
Syntax
regExpObj.lastIndex
Description
This property is set only if the regular expression used the "g"
flag to indicate a global search. The following rules apply:
- If
lastIndex
is greater than the length of the string, {{jsxref("RegExp.prototype.test()", "test()")}} and {{jsxref("RegExp.prototype.exec()", "exec()")}} fail, thenlastIndex
is set to 0. - If
lastIndex
is 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
lastIndex
is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, andlastIndex
is reset to 0. - Otherwise,
lastIndex
is set to the next position following the most recent match.
Examples
Example: Using lastIndex
Consider the following sequence of statements:
var re = /(hi)?/g;
Matches the empty string.
console.log(re.exec('hi')); console.log(re.lastIndex);
Returns ["hi", "hi"]
with lastIndex
equal to 2.
console.log(re.exec('hi')); console.log(re.lastIndex);
Returns ["", undefined]
, an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex
was 2 (and still is 2) and "hi"
has length 2.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition. | Standard | Initial definition. Implemented in JavaScript 1.2. JavaScript 1.5: lastIndex is a property of a {{jsxref("RegExp")}} instance, not the {{jsxref("RegExp")}} object. |
{{SpecName('ES5.1', '#sec-15.10.7.5', 'RegExp.lastIndex')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-properties-of-regexp-instances', 'RegExp.lastIndex')}} | {{Spec2('ES6')}} |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
See also
- {{jsxref("RegExp.prototype.ignoreCase")}}
- {{jsxref("RegExp.prototype.global")}}
- {{jsxref("RegExp.prototype.multiline")}}
- {{jsxref("RegExp.prototype.source")}}
- {{jsxref("RegExp.prototype.sticky")}}