Finding Matches with exec() and match()
You'll learn how to extract matched text from strings using two complementary methods: exec() on regex objects and match() on strings.
Now that you can test whether a pattern exists with test(), it's time to actually retrieve what matched. Think of it like the difference between asking "Is there a street address in this text?" versus "What is that address?"
Using exec() on Regex Objects
The exec() method is called on a regex pattern and returns detailed information about the first match:
const pattern = /cat/;
const text = "The cat sat on the mat";
const result = pattern.exec(text);
console.log(result);
// ["cat", index: 4, input: "The cat sat on the mat", groups: undefined]
console.log(result[0]); // "cat" - the matched text
console.log(result.index); // 4 - where the match starts
If no match is found, exec() returns null:
const noMatch = /dog/.exec("The cat sat");
console.log(noMatch); // null
Using match() on Strings
The match() method is called on the string itself and takes a regex as an argument:
const text = "The cat sat on the mat";
const result = text.match(/cat/);
console.log(result);
// ["cat", index: 4, input: "The cat sat on the mat", groups: undefined]
Notice the result format is identical to exec()! The difference is mainly in which object you call the method on: regex or string.
Key Takeaway: Use regex.exec(string) or string.match(regex) to extract matched text and get details like the match position. Both return an array with the match or null if nothing matched.