How-to
How to Replace Text Using Regex in JavaScript
String.replace and String.replaceAll accept a regex. Use the g flag for multi-match replace, $1/$2 for capture references, and a function for complex logic.
Basic replace
String.replace with a regex substitutes the first match. With the g flag, it replaces every match. String.replaceAll (ES2021+) REQUIRES the g flag when given a regex — it throws otherwise, as a safety check against accidentally replacing only the first match.
Collapse multi-spaces to single
Try this/\s+/gInput
'too much whitespace'.replace(/\s+/g, ' ')Result
'too much whitespace'Using capture groups in the replacement
Reference captured groups with $1, $2, ... in the replacement string. This is how you reorder or reshape matches without writing replacer logic. Named groups use $<name>.
Swap first-name/last-name
Try this/(\w+), (\w+)/Input
'Doe, Jane'.replace(/(\w+), (\w+)/, '$2 $1')Result
'Jane Doe'Replacer functions for complex logic
Pass a function as the second arg to String.replace. It receives the match, then each capture group, then offset and full-string. Return the replacement. Use this when the new value depends on the matched content — like uppercasing, computing from numbers, or conditional substitution.
Uppercase every word start
Try this/\b\w/gInput
'hello world'.replace(/\b\w/g, (c) => c.toUpperCase())Result
'Hello World'Escape sequences in replacement strings
In the replacement string, $ is special. Use $$ to produce a literal dollar sign. $& refers to the whole match, $` is the text before the match, $' is the text after. Mostly useful in one-off shell scripts; $1/$2 plus a replacer function covers nearly everything in production code.