index Property (RegExp) (JavaScript)

Returns the character position where the first successful match begins in a searched string. Read-only.




The object associated with this property is always the global RegExp object.

The index property is zero-based. The initial value of the index property is -1. Its value changes whenever a successful match is made.


The following example illustrates the use of the index property. This function iterates a search string and prints out the index and lastIndex values for each word in the string.

function RegExpTest()  
   var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())  
   if (ver < 5.5)  
      document.write("You need a newer version of JavaScript for this to work");  

   var src = "The quick brown fox jumps over the lazy dog.";  

   // Create regular expression pattern with a global flag.  
   var re = /\w+/g;  

   // Get the next word, starting at the position of lastindex.  
   var arr;  
   while ((arr = re.exec(src)) != null)  
      // New line:  
      document.write ("<br />");    
      document.write (arr.index + "-" + arr.lastIndex + " ");  
      document.write (arr);  


Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). See Version Information.

Applies To: RegExp Object

See Also

Regular Expression Syntax (JavaScript)