The lastIndex property of the RegExp object in JavaScript specifies the index at which to start the next match. It is read/write, and its value changes each time the regular expression successfully matches.
The syntax of RegExp.lastIndex property is:
lastIndex
This lastIndex property of RegExp the index at which to start the next match. It is an integer indicating the 0-based index in the string at which to start the search.
RegExp.lastIndex returns value of type Number
.
In JavaScript, we can use the lastIndex
property with a global regular expression to find successive matches in a string.
For example,
regex
with the global pattern /\d+/g
to match one or more digits.exec()
method to find the first match in the string '123 456 789'
and log the result and lastIndex
.exec()
again to find the next match and log the result and lastIndex
again.const regex = /\d+/g;
let result = regex.exec('123 456 789');
console.log(result); // [ '123', index: 0, input: '123 456 789', groups: undefined ]
console.log(regex.lastIndex); // 3
result = regex.exec('123 456 789');
console.log(result); // [ '456', index: 4, input: '123 456 789', groups: undefined ]
console.log(regex.lastIndex); // 7
[ '123', index: 0, input: '123 456 789', groups: undefined ] 3 [ '456', index: 4, input: '123 456 789', groups: undefined ] 7
In JavaScript, we can manually reset the lastIndex
property to control where the next search starts.
For example,
regex
with the global pattern /\d+/g
.exec()
method to find the first match in the string '123 456 789'
.regex.lastIndex
to 0.exec()
again to find the first match from the beginning of the string.const regex = /\d+/g;
let result = regex.exec('123 456 789');
console.log(result); // [ '123', index: 0, input: '123 456 789', groups: undefined ]
regex.lastIndex = 0;
result = regex.exec('123 456 789');
console.log(result); // [ '123', index: 0, input: '123 456 789', groups: undefined ]
[ '123', index: 0, input: '123 456 789', groups: undefined ] [ '123', index: 0, input: '123 456 789', groups: undefined ]
In JavaScript, the lastIndex
property does not affect non-global regular expressions.
For example,
regex
without the global flag, /\d+/
.regex.lastIndex
to 5.exec()
method to search for the pattern in the string '123 456 789'
.lastIndex
.const regex = /\d+/;
regex.lastIndex = 5;
const result = regex.exec('123 456 789');
console.log(result); // [ '123', index: 0, input: '123 456 789', groups: undefined ]
console.log(regex.lastIndex); // 0
[ '123', index: 0, input: '123 456 789', groups: undefined ] 0
In this JavaScript tutorial, we learned about lastIndex property of RegExp: the syntax and few working examples with output and detailed explanation for each example.