What is the role of lastIndex RegExp property in JavaScript?

HTMLJavascriptProgramming Scripts

The lastIndex RegExp property allows you to call those methods repeatedly, to loop through all matches in a string, and works only if the "g" modifier is set.

This property is read/write, so you can set it at any time to specify where in the target string, the next search should begin. exec() and test() automatically reset the lastIndex to 0 when they fail to find a match (or another match).

Example

You can try to run the following code to work with lastIndex RegExp property in JavaScript −

<html>
   <head>
      <title>JavaScript RegExp lastIndex Property</title>
   </head>
   <body>
      <script>
         var str = "JavaScript is an interesting scripting language";
         var re = new RegExp( "script", "g" );
         
         re.test(str);
         document.write("Test 1 - Current Index: " + re.lastIndex);
         
         re.test(str);
         document.write("<br />Test 2 - Current Index: " + re.lastIndex);
      </script>
   </body>
</html>
raja
Published on 26-Feb-2018 11:37:38
Advertisements