UP | HOME

Replace with callback in JavaScript

Of course, this is not new, it's already here centuries ago in the document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace, but I never have to do any replacement complicated enough to use it, so I pay no attention to it until I read a pull request from a teammate today.

The replace() command in JavaScript has a callback that provided you with some more information such as the matched content, the index and the original string. What you return in that callback will be replaced to the matched content.

This allows you to have a more complicated replacement, for example: you want to replace just the second occurrence of the letter "a" in "abcabcabc" to the letter "$".

How would you write a regex for that? What if we change the requirement to any nth occurrence? Even if you find a solution for this, is it elegant enough to not making any other developer vomit when they had to maintain your code?

Using replace() with a callback, we can just write:

"abcabcabc".replace(/a/g, (matched, index, original) => {
  if (index === 1) {
    return "$";
  } else {
    return matched;
  }
});

That's it, stop writing complicated regexes, start using replace() with callbacks, it makes things easier. You and your teammates, all have a life to live, and sanity to save.

Date: 2019-01-03 Thu 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41