JavaScript RegExp lastIndex Property

The JavaScript lastIndex property is used when we need to specify the index from where to start the next match. For example:

HTML with JavaScript Code
<!DOCTYPE html>

   <p id="res"></p>

      let myString = "JavaScript is fun. Is not it?";
      let myPattern = /is/gi;

      let myOutput = "";
         myOutput = myOutput + "At index number: " + myPattern.lastIndex + "<BR>";
      document.getElementById("res").innerHTML = myOutput;

That is, the is is available at two positions, one starts from index number 13 and the second one starts from index number 21.

Please note: The test() method is used to search a string for a match against a regular expression. It returns true on match, otherwise returns false.

Please note: We can only use the lastIndex property, if the g modifier is set while defining the regular expression pattern. This modifier is used to search for the specified string globally.

JavaScript lastIndex Syntax

The syntax of lastIndex property in JavaScript is:


It returns an integer value representing the index of the first character (of pattern's string) after the last match.

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this article? Share it!

Like/follow us on social media for updates!