String.prototype.replace supports replacement patterns

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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

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 defining a matching string and a replacing 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' ) ; msg . replace ( 'great' , '$&-$&' ) ; msg . replace ( 'great' , '$`' ) ; msg . replace ( 'great' , ` $' ` )

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