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).


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

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