This documentation is archived and is not being maintained.

exec Method

Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.

function exec(str : String) : Array


Required. The String object or string literal on which to perform the search.


If the exec method does not find a match, it returns null. If it finds a match, exec returns an array, and the properties of the global RegExp object are updated to reflect the results of the match. Element zero of the array contains the entire match, while elements 1 – n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the match method without the global flag (g) set.

If the global flag is set for a regular expression, exec searches the string beginning at the position indicated by the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the beginning of the string.

The array returned by the exec method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the match.


The following example illustrates the use of the exec method:

function RegExpTest() {
   var s = "";
   var src = "The rain in Spain falls mainly in the plain.";
   // Create regular expression pattern for matching a word.
   var re = /\w+/g;
   var arr;
   // Loop over all the regular expression matches in the string.
   while ((arr = re.exec(src)) != null)
      s += arr.index + "-" + arr.lastIndex + "\t" + arr + "\n";
   return s;


Version 3

See Also

match Method | RegExp Object | Regular Expression Syntax | search method | test Method

Applies To: Regular Expression Object