JS REGEX 09: Dynamic Text Replacement with replace() and Callback Functions in JavaScript

When most people think of string.replace(), they imagine something simple β replacing "old" with "new".
However, the replace() method can do much more. With callback functions, it becomes a flexible and intelligent transformation tool. You can perform replacements that depend on position, data, computation, or context.
π§ Understanding Callback Functions
A callback function is simply a function that is passed as an argument to another function. The receiving function executes it when certain conditions occur.
In replace(), JavaScript executes your callback for every match found by the regular expression. Whatever your callback function returns becomes the replacement text for that specific match.
This means you are no longer limited to static replacements β you can compute, transform, and decide dynamically what the replacement should be.
π Syntax of replace() with a Function
string.replace(regexp, function(match, group1, group2, ..., offset, fullString) {
// your logic
})
Parameters Explained:
- match β the exact substring that matched the regex.
- group1, group2, β¦ β any captured subgroups defined with parentheses
( ). - offset β the position (index) of the match in the original string.
- fullString β the entire string being processed.
If the regular expression includes the global flag g, the callback executes once for each match found.
πΉ Example 1 β Replacement Based on Position
Replace the first "Some" with "Start" and the second with "End".
const text = "Some string Some";
const result = text.replace(/Some/g, (match, offset) => {
return offset === 0 ? 'Start' : 'End';
});
console.log(result); // "Start string End"
Explanation:
- The regex
/Some/gmatches every"Some"in the string. - The callback runs twice β once per match.
- On the first call,
offsetis0, so"Start"is returned. - On the second call,
offsetis10, so"End"is returned. - The replacements depend on position, not just content.
πΉ Example 2 β Building Dynamic Templates
A callback can also replace placeholders dynamically from an object.
const template = "My name is {surname}, {name} {surname}";
const data = { name: "John", surname: "Doe" };
const result = template.replace(/{(.+?)}/g, (match, key) => data[key]);
console.log(result); // "My name is Doe, John Doe"
Explanation:
- The regex
/{(.+?)}/gcaptures text inside{ }braces. - The capturing group
( )stores the inner key name such as"name"or"surname". - The callback receives that key and returns the corresponding value from the
dataobject. - This approach forms the foundation of template engines like Handlebars or Mustache.
πΉ Example 3 β Mathematical Transformations
You can perform numeric computations inside the callback.
const text = "3 apples and 5 oranges";
const result = text.replace(/\d+/g, (num) => num * 2);
console.log(result); // "6 apples and 10 oranges"
Explanation:
- The regex
/\d+/gmatches all digit sequences. - Each number is passed into the callback as
num. - The callback doubles the value and returns it.
- The result is a dynamically computed string.
πΉ Example 4 β Case Transformation
Use a callback to transform text based on character type or position.
const sentence = "hello world";
const result = sentence.replace(/\b\w/g, (char) => char.toUpperCase());
console.log(result); // "Hello World"
Explanation:
- The regex
\b\wmatches the first letter after each word boundary. - The callback capitalizes each of these characters.
- The method returns a version of the string with every word capitalized.
π‘ Why Use Callback Functions in replace()?
Callback functions make your string operations context-aware and programmable. They let you:
- Compute new values dynamically (for example, multiplying numbers).
- Reference external data sources or objects.
- Respond to context, such as position or content.
- Apply conditional logic to decide when or how to replace text.
The functionβs return value is used for that specific match, making replace() behave almost like a mini transformation engine inside your string.
π§ͺ Practice Exercises
-
Replace every number in a string with its double. Example:
"4 cats and 7 dogs"β"8 cats and 14 dogs" -
Capitalize every first letter of a word. Example:
"learn javascript"β"Learn Javascript" -
Replace placeholders like
{city}in"Welcome to {city}"With data{ city: "Lagos" }β"Welcome to Lagos" -
Replace only even numbers in
"1 2 3 4 5"with"even". Result:"1 even 3 even 5" -
Replace each vowel with its uppercase version. Example:
"hello world"β"hEllO wOrld"
π§© Review Fill-Gap Questions
- A callback function is a function passed as an ____ to another function.
- In
replace(), the callback runs once for every ____ found. - The first parameter of the callback is always the ____ text.
- The
offsetparameter represents the matchβs ____ in the string. - Capturing groups inside the regex are returned as additional ____.
- The value returned by the callback becomes the actual ____ for that match.
- Using
/\d+/gmatches all sequences of ____. - To transform only the first letter of each word, use the boundary symbol ____.
- Callback-based replacements make
replace()more ____ and flexible. - In the template example,
data[key]retrieves the value corresponding to the ____ found inside{ }.