Learn JavaScript
❯ strings_regex.replace_regex
replace with Regex in JavaScript
$concept
String replace has two modes: string-pattern replaces the first occurrence only ("aaa".replace("a", "b") → "baa" — the classic surprise), while regex with /g replaces all ("aaa".replace(/a/g, "b") → "bbb"). Modern replaceAll covers the string-pattern all-occurrences case directly.
Replacement strings support $ patterns (
amp; whole match, $1 groups, $ literal dollar), and replacer functions ((match, g1, offset, string) => ...) compute dynamic replacements per match — case transforms, redactions, and templating without manual loops.$how it works
1
String pattern: first only
"aaa".replace("a", "b") → "baa" — single replacement is the default, the surprise, the bug.
2
Regex /g: all
"aaa".replace(/a/g, "b") → "bbb" — the global flag switches to every occurrence.
3
$ patterns reference
amp; (whole match), $1..$n (groups), $ (literal $) — match-aware replacements declaratively.4
Functions compute
Replacer callbacks receive match details per occurrence — dynamic rewrites loops can't express cleanly.
$example
console.log("aaa".replace("a", "b"));console.log("aaa".replace(/a/g, "b"));console.log("hi".replace(/(hi)/, "[$1]"));Output
baa
bbb
[hi]
1String pattern replaces only the first a — baa.
2Global regex replaces all three — bbb.
3$1 back-references the captured group — [hi].
$use cases
Global find-replace with /g (or replaceAll for string patterns)
Group-aware rewrites via $1-style back-references
Dynamic per-match transforms with replacer functions
Auditing single-replace calls that meant all-occurrences
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.