34

TIL: String.prototype.replace supports replacement patterns

 5 years ago
source link: https://www.tuicool.com/articles/VnyUraj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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... :see_no_evil:

It turns out that 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 .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK