Replacement Functions and Capture Groups
What You'll Learn
You'll learn how to use function callbacks with replace() and replaceAll() to perform smart, dynamic transformations based on what the pattern actually matched.
The Core Idea
Instead of passing a simple replacement string to replace() or replaceAll(), you can pass a function. JavaScript will call your function for each match, passing details about what was found, and use whatever your function returns as the replacement text.
Think of it like having a smart assistant: instead of saying "replace all apples with oranges," you're saying "every time you find an apple, ask me what to do with it—I'll decide based on the situation."
How It Works
When you use a function as the second argument, JavaScript passes these parameters to your callback:
- The full matched string
- Any capture groups (parenthesized parts of your regex)
- The position where the match was found
- The original string
let text = "I have 3 apples and 5 oranges";
let result = text.replace(/(\d+) (\w+)/g, function(match, number, fruit) {
return number * 2 + " " + fruit;
});
// "I have 6 apples and 10 oranges"
Here, (\d+) captures the number and (\w+) captures the fruit name. Your function receives both as separate arguments and can transform them however you want.
Common Use Cases
- Converting text case dynamically
- Performing calculations on matched numbers
- Building complex replacements based on context
- Formatting patterns like phone numbers or dates
Key Takeaway: Passing a function to replace() or replaceAll() lets you make intelligent, dynamic replacements based on exactly what was matched and captured, rather than using static replacement text.