Last active
July 31, 2019 17:09
-
-
Save stefanjudis/f0cf091b426c2411804dbcb31f2ed44a to your computer and use it in GitHub Desktop.
Suprising replacement patterns in String.prototype.replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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