JavaScript exec() Method
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). 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:
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".
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 | |||
---|---|---|---|