JS REGEX 09: Using String.replace() with a Callback Function in JavaScript
When you think of string.replace()
, you probably imagine swapping out all occurrences of one word with another โ like changing "old"
to "new"
. But what if you want to do something different for each match you find? Thatโs where callback functions shine.
A callback function is a function that you pass to another function so it can call your code when needed.
๐ง Key Idea
When you use string.replace()
with a regular expression and the global (g
) flag, you can pass a function instead of a replacement string. This function gets called every time a match is found โ and what it returns becomes the replacement for that match.
โ What the Callback Gets:
The function you pass to replace()
automatically receives:
- The matched text
- Text from any capturing groups (if used)
- The index of the match in the original string
- The entire original string
Letโs see this in action ๐
๐น Example 1: Changing Text Based on Position
Goal: Replace the first "Some"
with "Start"
and the second with "End"
.
const text = "Some string Some";
const result = text.replace(/Some/g, (match, offset, fullString) => {
if (offset === 0) {
return 'Start';
} else {
return 'End';
}
});
console.log(result); // "Start string End"
๐ Whatโs happening:
- First match:
"Some"
at index 0 โ callback returns"Start"
- Second match:
"Some"
at index 10 โ callback returns"End"
๐น Example 2: Filling in Template Strings
Goal: Replace {name}
and {surname}
in a template with values from an object.
const template = "My name is {surname}, {name} {surname}";
const data = { name: "John", surname: "Doe" };
const result = template.replace(/(?:{(.+?)})/g, (match, key) => {
return data[key];
});
console.log(result); // "My name is Doe, John Doe"
๐ Whatโs happening:
- The regex
/{(.+?)}/g
finds all placeholders like{name}
- The
key
inside the callback captures just the name (e.g."name"
) - We look up the value from the
data
object usingdata[key]
๐งช Practice Questions
Try these out to solidify your understanding:
-
Replace every number in a string with its double. Example:
"3 apples and 5 oranges"
โ"6 apples and 10 oranges"
-
Capitalize every word in a sentence. Example:
"hello world"
โ"Hello World"
-
Replace placeholders like
{city}
in a string with values from an object. Example:"Welcome to {city}"
, with{ city: "Lagos" }
โ"Welcome to Lagos"
-
Replace only even numbers in a string with
"even"
. Example:"1, 2, 3, 4"
โ"1, even, 3, even"
-
Replace each vowel in a sentence with its uppercase version. Example:
"hello"
โ"hEllO"
With replace()
+ callback functions, youโre not just swapping text โ youโre writing logic that responds to each match, dynamically. Powerful stuff.