0
0
JavascriptHow-ToBeginner · 3 min read

How to Use exec Method in JavaScript: Syntax and Examples

The exec method in JavaScript is used with regular expressions to search a string for a match and return detailed information about the match as an array. It returns null if no match is found. You call it like regex.exec(string) where regex is a regular expression.
📐

Syntax

The exec method is called on a regular expression object and takes a string as input. It returns an array with the matched text and capturing groups or null if no match is found.

  • regex: A regular expression object.
  • string: The text to search.
  • Returns: An array with match details or null.
javascript
const result = regex.exec(string);
💻

Example

This example shows how to use exec to find a word and extract parts of it using capturing groups.

javascript
const regex = /(\w+)@(\w+)\.com/;
const email = "hello@example.com";
const result = regex.exec(email);

if (result) {
  console.log("Full match:", result[0]);
  console.log("Username:", result[1]);
  console.log("Domain:", result[2]);
} else {
  console.log("No match found.");
}
Output
Full match: hello@example.com Username: hello Domain: example
⚠️

Common Pitfalls

One common mistake is using exec with a global regular expression (/g) and expecting it to always return the first match. With /g, exec remembers the last index and returns the next match on each call, which can be confusing.

Also, forgetting to check if the result is null before accessing array elements can cause errors.

javascript
const regex = /\d+/g;
const str = "123 456";

console.log(regex.exec(str)); // First match
console.log(regex.exec(str)); // Second match
console.log(regex.exec(str)); // null - no more matches

// Correct way to loop all matches:
let match;
while ((match = regex.exec(str)) !== null) {
  console.log(`Found ${match[0]} at index ${match.index}`);
}
Output
[ '123', index: 0, input: '123 456', groups: undefined ] [ '456', index: 4, input: '123 456', groups: undefined ] null Found 123 at index 0 Found 456 at index 4
📊

Quick Reference

  • exec(string): Searches for a match in string.
  • Returns an array with match info or null.
  • Use capturing groups (...) to extract parts.
  • With /g flag, repeated calls find successive matches.
  • Always check for null before accessing results.

Key Takeaways

Use exec on a regex to find matches and get detailed match info.
Remember exec returns null if no match is found.
With the global flag /g, exec returns successive matches on repeated calls.
Always check the result of exec before accessing array elements to avoid errors.
Capturing groups in regex help extract specific parts of the matched string.