JavaScript lastIndex Property

The lastIndex property in JavaScript is used with regular expressions to track the position where the next search will begin. It only works with the global (g) flag and automatically updates after each match.

Syntax

regexObject.lastIndex

How lastIndex Works

The lastIndex property starts at 0 and updates to the position after each match when using exec() or test() with the global flag.






JavaScript lastIndex Property



Finding Multiple Matches with lastIndex

Text: The king bought an expensive ring.

Search pattern: /ing/g

Match 1: 'ing' found at index 7
lastIndex after match 1: 10

Match 2: 'ing' found at index 31
lastIndex after match 2: 34

Match 3: null
lastIndex after match 3: 0

Using test() Method

The test() method also updates lastIndex with global regex:





Testing: cat bat rat
Pattern: /at/g

Match found, lastIndex: 3
Match found, lastIndex: 7
Match found, lastIndex: 11
No more matches, lastIndex: 0

Resetting lastIndex

You can manually reset lastIndex to start searching from the beginning:





First search:
Found at lastIndex: 5
Found at lastIndex: 17

Resetting lastIndex to 0

Second search:
Found at lastIndex: 5
Found at lastIndex: 17

Key Points

  • lastIndex only works with the global (g) flag
  • It automatically resets to 0 when no more matches are found
  • You can manually set lastIndex to control where the next search begins
  • Without the global flag, lastIndex is always 0

Conclusion

The lastIndex property is essential for tracking position in global regex searches. It automatically updates after each match and resets when no more matches are found, making it perfect for iterating through all occurrences in a string.

Updated on: 2026-03-15T23:18:59+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements