How Regex Replacement Works
JavaScript's String.replace() takes a regex pattern and a replacement string. The regex finds matches, and each match is substituted with the replacement. With the global (g) flag, all matches are replaced. Without it, only the first match is replaced. The replacement string supports special tokens for referencing captured groups.
Replacement Tokens Reference
$1, $2, $3... insert captured group values by number. $<name> inserts a named group. $& inserts the entire match. $` inserts text before the match. $' inserts text after the match. $$ inserts a literal dollar sign.
Real-World Use Cases
Reformatting dates from MM/DD/YYYY to YYYY-MM-DD. Swapping first and last names. Converting camelCase to snake_case. Cleaning CSV data. Removing HTML tags. Normalizing phone numbers. Adding markup to plain text. All of these are regex replace operations you can test here before running on real data.