Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I came across a blog post (it's in German though) written by Peter Kröner and learned something.

The article describes the not so well known behaviors of the method String.prototype.replace. Using this method is usually very straight forward. It supports regular expressions if you need to, but for most cases, it's about replacing a matched string.

That's at least what I thought... 🙈

It turns out that if the second argument is a string (it can also be a function) and includes specific character sequences like $& or $' "replacer magic" appears.

const msg = 'This is a great message';

msg.replace('great', 'wonderful'); 
// "This is a wonderful message"
//
// -> 'great' is replaced by 'wonderful'

msg.replace('great', '$&-$&');
// "This is a great-great message"
// '$&' represents the matched substring
//
// -> 'great' is replaced by 'great-great'

msg.replace('great', '$`');
// "This is a This is a  message"
// '$`' represents the string before the matched string
//
// -> 'great' is replaced by 'This is a '

msg.replace('great', `$'`)
// "This is a  message message"
// `$'` represents the string after the matched string
//
// -> 'great' is replaced by ' message'

Oh my..., this behavior can lead to very hard to spot bugs!

If you want to read more about it, have a look at the replace docs on MDN or this overview on replacement values.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles