JavaScript exec() Method |
This tutorial explains the exec() method in JavaScript, which is used to execute a regular expression on a string and return detailed match information.
Definition and Usage
The exec() method executes a search for a match in a string. It returns an array containing the matched text and any captured groups, or null if no match is found.
Syntax
regexp.exec(string)
Parameters
| Parameter | Description |
|---|---|
string |
The string to search within. |
Return Value
Returns an array with the matched text and captured groups, or null if no match is found.
Example
Here's how to use the exec() method:
const regex = /(d{3})-(d{4})/;
const str = "My number is 123-4567.";
const result = regex.exec(str);
console.log(result); // Output: ["123-4567", "123", "4567", index: 14, input: "My number is 123-4567.", groups: undefined]
Key Points
- If the regular expression has no global flag (
g),exec()will return the first match. - If the regular expression has the global flag (
g), each call toexec()will return the next match from where the last one left off. - The returned array includes the full match at index 0, followed by captured groups.
- The
indexproperty shows the position of the match in the string. - The
inputproperty contains the original string that was searched.
Practical Use Cases
The exec() method is useful when you need detailed information about matches, such as capturing specific parts of a string (e.g., extracting phone numbers, email addresses, or dates).
Related Methods
- test() β Tests whether a pattern exists in a string.
- match() β Returns all matches of a pattern in a string.
- matchAll() β Returns an iterator of all matches.
YouTip