JavaScript RegExp exec() Method (original) (raw)
Last Updated : 05 Dec, 2024
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."); }
`
Output
Full match: 12-09-2023 Day: 12 Month: 09 Year: 2023
- **Regular Expression: /(\d{2})-(\d{2})-(\d{4})/ matches a date in the format dd-mm-yyyy. The parentheses () are used to capture groups.
- **exec() method: Searches the string for the pattern and returns an array with detailed match information:
- **res[0]: The full matched string.
- **res[1], res[2], res[3]: The captured groups (day, month, and year).
- If no match is found, exec() returns null.
**Syntax:
let result = regex.exec(string);
- **regex: The regular expression to search for in the string.
- **string: The string to search within.
- **result: An array of match details if a match is found, or null if no match is found.
**Now let's see some uses of RegExp exec() Method
1. Extracting Email Components
Let’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."); }
`
Output
Domain: example.com
2. 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); }
`
Output
Found: 2 at position: 7 Found: 15 at position: 20
Key Points About exec()
- **Detailed Match Information: exec() provides detailed information about the match, including the matched string, capture groups, the match's index in the input string, and the original input.
- **Global Flag (g): When used with the g flag, exec() can find all matches in the string, returning results in a loop.
- **Returns null on No Match: If no match is found, exec() returns null.