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

**Syntax:

let result = regex.exec(string);

**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()