Matching With .exec()

Download javascript eBook

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'

Stats

Contributors: 3
2016-08-12
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook