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/g matches every "Some" in the string.
  • The callback runs twice β€” once per match.
  • On the first call, offset is 0, so "Start" is returned.
  • On the second call, offset is 10, 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 /{(.+?)}/g captures 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 data object.
  • 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+/g matches 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\w matches 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

  1. Replace every number in a string with its double. Example: "4 cats and 7 dogs" β†’ "8 cats and 14 dogs"

  2. Capitalize every first letter of a word. Example: "learn javascript" β†’ "Learn Javascript"

  3. Replace placeholders like {city} in "Welcome to {city}" With data { city: "Lagos" } β†’ "Welcome to Lagos"

  4. Replace only even numbers in "1 2 3 4 5" with "even". Result: "1 even 3 even 5"

  5. Replace each vowel with its uppercase version. Example: "hello world" β†’ "hEllO wOrld"


🧩 Review Fill-Gap Questions

  1. A callback function is a function passed as an ____ to another function.
  2. In replace(), the callback runs once for every ____ found.
  3. The first parameter of the callback is always the ____ text.
  4. The offset parameter represents the match’s ____ in the string.
  5. Capturing groups inside the regex are returned as additional ____.
  6. The value returned by the callback becomes the actual ____ for that match.
  7. Using /\d+/g matches all sequences of ____.
  8. To transform only the first letter of each word, use the boundary symbol ____.
  9. Callback-based replacements make replace() more ____ and flexible.
  10. In the template example, data[key] retrieves the value corresponding to the ____ found inside { }.

<
Previous Post
πŸ•’ Build a Digital Clock with JavaScript + Time-Based Greeting
>
Next Post
πŸ’» Project: Building a Simple Login Page with JavaScript Credentials