A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-regexp-lastindex-property/ below:

JavaScript RegExp lastIndex Property - GeeksforGeeks

JavaScript RegExp lastIndex Property

Last Updated : 11 Jul, 2025

The lastIndex property of a JavaScript regular expression object indicates the index at which to start the next match. This property is particularly useful when using methods like exec() or test() in combination with global (g) or sticky (y) flags.

JavaScript
let regex = /test/g;
// Regular expression with 'g' flag
let str = "test test";
regex.exec(str); 
console.log(regex.lastIndex); 
regex.exec(str); 
console.log(regex.lastIndex); 
Syntax:
regex.lastIndex
Key Points Real-World Examples 1. Iterating Through Matches JavaScript
let regex = /\d+/g; // Match digits
let str = "123 456 789";
let match;
while ((match = regex.exec(str)) !== null) {
    console.log(`Matched: ${match[0]}, Next search starts at: ${regex.lastIndex}`);
}

The lastIndex property ensures that matches are found sequentially.

2. Using lastIndex with Sticky Regex JavaScript
let regex = /\d+/y; 
// Sticky regex
let str = "123 456";
regex.lastIndex = 4; 
// Start search from index 4
console.log(regex.exec(str));
console.log(regex.lastIndex);

With the y flag, the regex only matches if the lastIndex position aligns with the match.

3. Manually Resetting lastIndex JavaScript
let regex = /hello/g;
let str = "hello world hello";

regex.lastIndex = 6; 
// Start searching from index 6
console.log(regex.exec(str)); 
console.log(regex.lastIndex); 

You can manually set lastIndex to skip certain portions of the string.

4. Testing Without Resetting JavaScript
let regex = /foo/g;
let str = "foo bar foo";

regex.test(str);
 // Finds the first "foo"
console.log(regex.lastIndex);

regex.test(str);
 // Finds the second "foo"
console.log(regex.lastIndex); 

With the g flag, lastIndex is updated after every test() call.

5. Resetting on No Match JavaScript
let regex = /abc/g;
let str = "abc def";

regex.lastIndex = 4;
 // Start at index 4
console.log(regex.exec(str)); 
console.log(regex.lastIndex);

If no match is found, lastIndex resets to 0.

Why Use the lastIndex Property? Conclusion

The lastIndex property is a powerful feature for working with regular expressions in JavaScript, offering fine-grained control over how and where matching starts. It’s especially useful in scenarios requiring iterative or position-based matching.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4