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.
Your code is not completely correct. The
index
variable in the callback is actually the position of the match in the string. So if the task is still matching the 2nd occurrence in the string, your code will fail for this string: "abcabca" and the index for each match will be0
,3
,8
and not0
,1
,2
. However, we can just add a variable to count the index of each occurrence so overall, nice discovery.Fun fact: That
index
variable is also accessible in the regex itself using the lastIndex property.