Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

RegExp lastIndex — the next match position

lastIndex stores the next search position for regular expressions with g or y. It is a writable property of each RegExp instance, not a prototype property.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

regexp.lastIndex
regexp.lastIndex = index

Despite the label RegExp.prototype.lastIndex, lastIndex is an own property of each RegExp instance, initially 0. It is writable, non-enumerable, and non-configurable. Positions count UTF-16 code units, not user-perceived characters.

For built-in exec() and test(), lastIndex is the starting search position with g or y. With g but not y, the search can find a match at a later position; with y, it does not try later positions. In Unicode mode (u or v), if lastIndex points to the low surrogate of a valid UTF-16 pair, a sticky match can start at the preceding high surrogate. Success sets the index just after the match; failure resets it to zero, including when it exceeds the string length. Even without either flag, the built-in matcher reads lastIndex and applies ToLength to its value. If the conversion succeeds, the matcher starts searching at 0 and does not update the property. If the value is a Symbol, the conversion throws a TypeError and no search starts.

You can assign regexp.lastIndex = index; the value undergoes ToLength conversion when used. State belongs to the expression, not the string: set lastIndex = 0 or create another instance before an independent search. Repeated test() calls with g or y also change state.

An empty match in exec() does not automatically advance the index, so a naive loop can run forever. The example uses nonempty matches and demonstrates progress, resetting after failure, and manual resumption.

Examples

const re = /a/g;
const text = "a_a";
console.log(re.test(text), re.lastIndex);
console.log(re.test(text), re.lastIndex);
console.log(re.test(text), re.lastIndex);
re.lastIndex = 2;
console.log(re.exec(text).index, re.lastIndex);

Result

true 1
true 3
false 0
2 3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources