Matching With .exec
suggest changeMatch Using .exec()
RegExp.prototype.exec(string) returns an array of captures, or null if there was no match.
const re = /([0-9]+)[a-z]+/;
const 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()
const re = /a/g;
let result;
while ((result = re.exec('barbatbaz')) !== null) {
console.log("found '" + result[0] + "', next exec starts at index '" + re.lastIndex + "'");
}
The g flag is required. Without it, lastIndex stays 0 and this loop never ends.
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’
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents