Name

RegExp.exec( ) — general-purpose pattern matching

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Synopsis

                  regexp.exec(string)

Arguments

string

The string to be searched.

Returns

An array containing the results of the match, or null if no match was found. The format of the returned array is described below.

Throws

TypeError

If this method is invoked on an object that is not a RegExp.

Description

exec( ) is the most powerful of all the RegExp and String pattern matching methods. It is a general-purpose method that is somewhat more complex to use than RegExp.test( ), String.search( ), String.replace( ), and String.match( ).

exec( ) searches string for text that matches regexp. If it finds a match, it returns an array of results; otherwise, it returns null. Element 0 of the returned array is the matched text. Element 1 is the text that matched the first parenthesized subexpression, if any, within regexp. Element 2 contains the text that matched the second subexpression, and so on. The array length property specifies the number of elements in the array, as usual. In addition to the array elements and the length property, the value returned by exec( ) also has two other properties. The index property specifies the character position of the first character of the matched text. The input property refers to string. This returned array is the same as the array that is returned by the String.match( ) method, when invoked on a nonglobal RegExp object.

When exec( ) is invoked on a ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.