Accessing Captured Values with match()
You'll learn how to extract specific parts of a string using match() and capture groups—perfect for pulling out exact pieces of data you need.
How match() Works with Capture Groups
While exec() gives you one match at a time, String.prototype.match() without the global flag returns an array containing the full match plus all captured groups in one shot. It's like getting a shopping receipt: the first item is your total purchase, and the rest are individual items you bought.
When you call match() on a string with a regex that has parentheses (capture groups), you get back an array where:
- Index
[0]is the entire matched string - Index
[1]is the first capture group - Index
[2]is the second capture group - And so on...
Example Without Global Flag
const text = "John Smith";
const pattern = /(\w+) (\w+)/;
const result = text.match(pattern);
console.log(result[0]); // "John Smith" (full match)
console.log(result[1]); // "John" (first capture group)
console.log(result[2]); // "Smith" (second capture group)
The array also includes helpful properties like index (where the match started) and input (the original string), just like with exec().
When to Use match() vs exec()
Use match() when you want a simple, one-time extraction from a string. It's cleaner than exec() for single matches because you call it directly on the string. Think of it as the "grab and go" version—less ceremony, same power.
Key Takeaway: Without the global flag, match() returns an array with the full match at index 0 and each capture group at subsequent indexes, making it ideal for extracting structured data from strings in one call.