JavaScript Matching With .exec()


Example

Match Using .exec()

RegExp.prototype.exec(string) returns an array of captures, or null if there was no match.

var re = /([0-9]+)[a-z]+/;
var match = re.exec("foo123bar");

match.index is 3, the (zero-based) location of the match.

match[0] is the full match string.

match[1] is the text corresponding to the first captured group. match[n] would be the value of the nth captured group.

Loop Through Matches Using .exec()

var re = /a/g;
var result;
while ((result = re.exec('barbatbaz')) !== null) {
    console.log("found '" + result[0] + "', next exec starts at index '" + re.lastIndex + "'");
}

Expected output

found 'a', next exec starts at index '2'
found 'a', next exec starts at index '5'
found 'a', next exec starts at index '8'