JavaScript Regular Expression exec Method

If this post helps you, click an ad

exec() is a pattern-matching method of the RegExp object. It receives as its argument a string. This string is tested for a match against a regular expression. exec() returns an array, if a match occurred. If no match occurred, null is returned. exec() should be used when a returned array is wanted. This array is described below. If a string is being tested against a regular expression for true or false only, the test() method should be used instead of exec().

The match array is constructed as follows:

Element 0: Contains the found match
Elements 1-n: Contain the matches for parenthesized items in the regular expression

The match array also has two properties:

index: The position in the string where the match occurred
input: The string that was searched

var re = /late(r?)/;
var aryExec = re.exec('I was later than him');

The preceding example will match either 'late' or 'later.' In the example given, the exec() match array contains:

aryExec[0] = later (The match)
aryExec[1] = r (The parenthesized match)

The array properties contain:

aryExec.index = 6 (Where the match began in the string. Counting starts at 0.)
aryExec.input = I was later than him (The string that was searched.)

Leave a Reply