match(): Extracting Pattern Matches
What you'll learn: How to pull out all occurrences of a pattern from a string using the match() method with regular expressions.
While search() tells you where a pattern is found, match() actually extracts the matching text and returns it to you in an array.
How match() Works
The match() method searches a string for patterns and returns an array containing the matches. If no match is found, it returns null instead.
Basic syntax:
string.match(pattern)
The pattern is typically a regular expression. Think of match() like a highlighter that not only marks text but also copies the highlighted portions into a list for you.
Simple Example
let text = "My phone is 555-1234";
let result = text.match(/\d+/); // Find first sequence of digits
console.log(result); // ["555"]
Global Matching
Add the g flag to find all matches, not just the first:
let sentence = "I have 3 cats and 5 dogs";
let numbers = sentence.match(/\d+/g);
console.log(numbers); // ["3", "5"]
Without the g flag, you get only the first match plus extra information. With g, you get an array of all matches.
When There's No Match
let text = "hello world";
let result = text.match(/\d+/);
console.log(result); // null
Always check if the result is null before using it!
Key Takeaway: Use match() to extract matching text from a string based on a pattern—it returns an array of matches (with the g flag) or null if nothing matches.