exec Method

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



Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags.
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 ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
  if (ver >= 5.5){                 //Test JScript version.
    var src = "The rain in Spain falls mainly in the plain.";
    var re = /\w+/g;               //Create regular expression pattern.
    var arr;
    while ((arr = re.exec(src)) != null)
       document.write(arr.index + "-" + arr.lastIndex + "\t" + arr);
    alert("You need a newer version of JScript for this to work");


Version 3

See Also

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

Applies To: Regular Expression Object