JavaScript exec() Method RegExp.exec() Method (Regular Expressions)

This tutorial introduces you to the exec() method, from JavaScript's RegExp object. The exec() method is applied on a regular expression pattern, and takes a string as argument (the string in which to search for the pattern). JavaScript exec() method's syntax The exec() method returns null if no match was found, or an array containing the matching results when successful. The matching strings are incrementally added to the returned array, which means that you can search while returning results, using a JavaScript while-loop, for example.

Unlike the test() method, which returns true (if it found a match) or false, the exec() method returns null or an array of matched patterns.

This makes the exec() method an ideal choice for more involved pattern matching operations, while test() is best suited for quick data validation, for example.

Compare the Regexp object's exec() method with the similar String object's match() method.

Using the exec() Method

JavaScript's exec() method takes one argument, a literal string or string variable, designating the string in which to search. The exec() method is applied on a regular expression pattern, representing the pattern for which to search inside the string argument. The script below looks for any occurrence of a number.

Remember: the exec() method returns either an array, if it found at least one match, or null, if it did not find any match.

// Declare a regular expression using literal notation
var remo = /\d/;
var carter = "This string does not contain any number";
alert( remo.exec( carter ) );

The exec() method did not find any match for numbers inside our string: JavaScript exec() method returning a null value

Knowing to expect a potential null returned value allows you to handle it appropriately in your scripts. We will next see how to use the data returned by a successful exec() match, an array of matched patterns.

Handling Arrays Returned by the exec() Method

If the exec() method does not return null, you know that it has found at least one match to the pattern supplied. The following script gathers all successful matches, and finally displays them.

// Re-use our number-matching regular expression
var remo = /\d/g;
var carter = "Step 2: add 4 to 5 pinches of salt";
var matched = null;

// Retrieve matches until null is returned
while( (matched=remo.exec(carter)) != null )
    alert( matched[0] );

Our script returned three alerts, respectively displaying "2", "4", and "5". JavaScript exec() method

Test the exec() Method

Interactively test the exec() method by editing the JavaScript code below and clicking the Test exec() Method button.

Browser support for JavaScript exec() method
Internet Explorer supports the JavaScript exec() methodFirefox supports the JavaScript exec() methodSafari supports the JavaScript exec() methodOpera supports the JavaScript exec() method