This documentation is archived and is not being maintained.

match Method

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

function match(rgExp : RegExp) : Array

Arguments

rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Can also be a variable name or string literal containing the regular expression pattern and flags.

Remarks

If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match.

The array returned by the match 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 last match.

If the global flag (g) is not set, 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 exec method without the global flag set. If the global flag is set, elements 0 - n contain all matches that occurred.

Example

The following example illustrates the use of the match method.

function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/i;    //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return first occurrence of "ain".
}

This example illustrates the use of the match method with the g flag set.

function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/ig;      //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return array containing all four
                      // occurrences of "ain".
}

The following lines of code illustrate the use of a string literal with the match method.

var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");

Requirements

Version 3

See Also

exec Method | RegExp Object | replace Method | search Method | test Method

Applies To: String Object

Show: