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>
<html>
<body>

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

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

      let myOutput = "";
      while(myPattern.test(myString)==true)
         myOutput = myOutput + "At index number: " + myPattern.lastIndex + "<BR>";
            
      document.getElementById("res").innerHTML = myOutput;
   </script>
   
</body>
</html>
Output

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:

RegExpObj.lastIndex

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 »



Like/Share Us on Facebook 😋