Skip to content

Instantly share code, notes, and snippets.

@breeze1990
Created June 12, 2015 00:33
Show Gist options
  • Save breeze1990/063f48cf66bf437a4989 to your computer and use it in GitHub Desktop.
Save breeze1990/063f48cf66bf437a4989 to your computer and use it in GitHub Desktop.
JavaScript string replace with subgroups
// \1 \2... can refer to matched subgroup and be used in regex
// $1 $2... can refer to matched subgroup and be used in newString
//
"abba".replace(/(a)(b)\2\1/g,"$2$2$1$1$1") // =="bbaaa"
// What if I want to insert "$1" literally in newString
// $$ can be used
"abba".replace(/(a)(b)\2\1/g,"$$1$2$1") // =="$1ba"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment