Skip to content

Instantly share code, notes, and snippets.

@stefanjudis
Last active July 31, 2019 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanjudis/f0cf091b426c2411804dbcb31f2ed44a to your computer and use it in GitHub Desktop.
Save stefanjudis/f0cf091b426c2411804dbcb31f2ed44a to your computer and use it in GitHub Desktop.
Suprising replacement patterns in String.prototype.replace
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment