TIL: JavaScript replace() command with callback

huytd

Huy Tr.

Posted on January 4, 2019

TIL: JavaScript replace() command with callback

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 "abcabc"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 regex solution, 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:

"abcabc".replace(/a/g, (matched, index, original) => {
  if (index !== 0) {
    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.

💖 💪 🙅 🚩
huytd
Huy Tr.

Posted on January 4, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related