myRegExp.exec( sourceString ) in ECMAScript 262

Run the regular expression against a string and return a single match.

Arguments

nametypedescription
sourceString String The string to run the regular<
Return Type
Array

Description

If the regular expression cannot be matched in the string, null is returned. Upon a successful match, the return value is an array, with two custom properties:

var sentence = "The quick brown fox jumped over the lazy dog.";
var vowelFollowedByConsonants = /[aeiou]([^aeiou. ]+)/gi;
var firstMatch = vowelFollowedByConsonants.exec(sentence);

// ** firstMatch[0] is "ick" ... the first match found
// ** firstMatch[1] is "ck" ... the first captured expression
// ** firstMatch.index is 6 ... the location of the start of the match
// ** firstMatch.input is "The quick brown fox jumped over the lazy dog."

In the above, note that setting the global flag did not cause all the various instances to be returned. Unlike String.match(), this method only returns information about a single match. However, if the global flag is set, the lastIndex property of the regular expression is used to determine where to start the search, and is updated with each call to exec(). The following example finds all matches:

var sentence = "The quick brown fox jumped over the lazy dog.";
var vowelFollowedByConsonants = /[aeiou]([^aeiou. ]+)/gi;
var allMatches = "";

var aMatch = vowelFollowedByConsonants.exec(sentence);
while (aMatch!=null){
    allMatches+="'"+aMatch[0]+"' was found at "+aMatch.index+"\n";
    aMatch = vowelFollowedByConsonants.exec(sentence);
}
/****************************************************
allMatches is the following multi-line string:
'ick' was found at 6
'own' was found at 12
'ox' was found at 17
'ump' was found at 21
'ed' was found at 24
'ov' was found at 27
'er' was found at 29
'azy' was found at 37
'og' was found at 42
****************************************************/

Sometimes parentheses are needed to logically group portions of the regular expression, but are not wanted in the captured output. To achieve this effect, use a non-capturing expression, (?:...). The following example uses a non-capturing expression to allow a price without cents (e.g. "$14") to be matched, while keeping only the dollars and cents as captured subexpressions:

var sentence = "You bought 4 items. The total price is $ 14.37.";
var priceMatch = /the total price is \$\s*(\d+)(?:\.(\d{2}))?/i;
var price = priceMatch.exec(sentence);

// ** price[0] is "The total price is $ 14.37"
// ** price[1] is "14"
// ** price[2] is "37"
// ** price.index is 20
// ** price.input is "You bought 4 items. The total price is $ 14.37."