Last Updated : 11 Jul, 2025
The RegExp.exec() method in JavaScript allows you to search for a pattern in a string and retrieve detailed information about the match. Unlike simple methods like test(), exec() returns not just a boolean, but an array containing the entire match, capturing groups, the position of the match, and more.
JavaScript
let regex = /(\d{2})-(\d{2})-(\d{4})/;
let s = "Today's date is 12-09-2023.";
let res = regex.exec(s);
if (res) {
console.log("Full match:", res[0]);
console.log("Day:", res[1]);
console.log("Month:", res[2]);
console.log("Year:", res[3]);
} else {
console.log("No match found.");
}
Full match: 12-09-2023 Day: 12 Month: 09 Year: 2023
Syntax:
let result = regex.exec(string);
Now let's see some uses of RegExp exec() Method
1. Extracting Email ComponentsLet’s use exec() to extract the domain from an email address:
JavaScript
let regex = /@([a-zA-Z0-9.-]+)/;
let mail = "user@example.com";
let res = regex.exec(mail);
if (res) {
console.log("Domain:", res[1]);
} else {
console.log("No domain found.");
}
Domain: example.com2. Finding All Digits in a String
You can use exec() with the global flag (g) to find all occurrences of digits in a string
JavaScript
let regex = /\d+/g;
let s = "I have 2 apples and 15 bananas.";
let res;
while ((res = regex.exec(s)) !== null) {
console.log("Found:", res[0], "at position:", res.index);
}
Found: 2 at position: 7 Found: 15 at position: 20Key Points About exec()
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4