String.prototype.replace() returns a new string with matches of a pattern swapped for a replacement (same API as MDN String.prototype.replace()). Learn string vs regex patterns, the g flag, capture groups, replacer functions, five examples, and try-it labs.
01
Kind
Instance method
02
Returns
New string
03
String pattern
First match only
04
Regex + g
All matches
05
Mutates?
No
06
Baseline
Widely available
Fundamentals
Introduction
Need to swap one word for another, clean up a pattern, or rewrite part of a string with logic? replace() builds a new string from the old one by substituting matches.
Pass a string as the pattern and only the first match is replaced. Pass a RegExp with the g flag to replace every match. The second argument can be a plain string (with special $ patterns) or a function.
💡
Beginner tip
Want every occurrence of a plain string? Prefer replaceAll(), or use a regex with the g flag. Plain replace("a", "b") stops after the first "a".
Examples follow MDN String.replace() patterns. Use View Output or Try It Yourself for each case.
📚 Getting Started
Replace one match, then use regex flags.
Example 1 — Basic String and Word Replace
MDN demo: replace a literal, then a word-boundary regex.
JavaScript
const paragraph = "This dog's name is just Dog! Yes, that is the name.";
paragraph.replace("name", "nickname");
// "This dog's nickname is just Dog! Yes, that is the name."
paragraph.replace(/\bis\b/, "was");
// "This dog's name was just Dog! Yes, that is the name."
paragraph.replace(/\bis\b/g, "was");
// "This dog's name was just Dog! Yes, that was the name."
This dog's nickname is just Dog! Yes, that is the name.
This dog's name was just Dog! Yes, that is the name.
This dog's name was just Dog! Yes, that was the name.
How It Works
The literal "name" swaps only the first occurrence. Without g, the regex also stops after the first is. With g, both word-boundary matches become was.
Example 2 — Ignore Case with a Regex
MDN demo: the i flag matches regardless of capitalization.
JavaScript
const str = "Twas the night before Xmas...";
const newStr = str.replace(/xmas/i, "Christmas");
newStr;
// "Twas the night before Christmas..."
/xmas/i matches "Xmas" even though the letters differ in case. Without i, that search would fail.
📈 Practical Patterns
Global replace, capture groups, and replacer functions.
Example 3 — Global + Ignore Case
MDN demo: replace every apples (any case) with oranges.
JavaScript
const re = /apples/gi;
const str = "Apples are round, and apples are juicy.";
const newStr = str.replace(re, "oranges");
newStr;
// "oranges are round, and oranges are juicy."
Each capital letter match is lowercased. If it is not at index 0, a hyphen is inserted before it. Functions are required when you need to transform the match before inserting it.
Applications
🚀 Common Use Cases
Fix one typo / token — swap the first occurrence of a word.
Global cleanup — regex with g (or replaceAll) for every match.
Case-insensitive edits — add the i flag.
Reorder parts — capture groups with $1 / $2.
Dynamic transforms — pass a function for per-match logic.
Not for reading matches — use match() / matchAll() when you only need the hits.
🧠 How replace() Builds the Result
1
Read pattern + replacement
Accept a string/RegExp pattern and a string or function replacement.
Input
2
Find matches
Search once, or repeatedly when the regex has the g flag.
Search
3
Build replacement text
Expand $ patterns, or call the replacer function for each match.
Swap
4
✅
Return a new string
The original str is unchanged.
Important
📝 Notes
A string pattern replaces only the first match.
Only a regex with the g flag replaces multiple times via replace().
Special $ patterns work in string replacements, not in values returned from a function.
Empty string pattern prepends the replacement: "xxx".replace("", "_") → "_xxx".
Prefer replaceAll() when you clearly want every literal occurrence.
Always capture the return value — the original string does not update in place.
Compatibility
Browser & Runtime Support
String.prototype.replace() is Baseline Widely available — supported across modern browsers since July 2015 (and far earlier as a core language feature).
✓ Baseline · Widely available
String.replace()
Safe for production in browsers and runtimes (Node.js, Deno, Bun). Use a g-flag regex or replaceAll() when you need every match.
UniversalWidely available
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
replace()Excellent
Bottom line: Use String.replace() to swap matches for new text. Remember: string patterns replace once; use /g or replaceAll() for every occurrence.
Wrap Up
Conclusion
String.prototype.replace() is the standard way to rewrite parts of a string — from a single literal swap to global regex transforms and custom replacer functions. Choose the pattern carefully, and reach for replaceAll() when “every occurrence” is the goal.
Add the g flag (or use replaceAll) for every match
Use capture groups / $n to reorder parts
Use a function when the replacement must be computed
Assign the return value to a new variable
❌ Don’t
Expect replace("a", "b") to change every "a"
Forget that strings are immutable
Rely on $1 with a string pattern (groups need a RegExp)
Call .toLowerCase() on "$&" before replace — use a function instead
Use replace when you only need to inspect matches
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about String.replace()
Swap matches for new text without mutating the original.
5
Core concepts
📝01
Returns
new string
API
🔎02
String pattern
first only
Rule
🎯03
All matches
/g or replaceAll
Tip
⚡04
Groups
$1 $2 …
Regex
📄05
Mutates
no
Immutable
❓ Frequently Asked Questions
String.prototype.replace(pattern, replacement) returns a new string where matches of pattern are swapped for replacement. A plain string pattern replaces only the first match. A RegExp with the g flag can replace every match.
No. Strings are immutable. replace() returns a new string; the original stays the same.
Use a regular expression with the g (global) flag, or use String.prototype.replaceAll() for a clearer all-matches API.
Yes. Pass a function as the second argument. It runs for each match and its return value becomes the replacement text. Special $ patterns do not apply to that return value.
When pattern is a RegExp with capturing groups, $1 inserts the first group, $2 the second, and so on. $$ inserts a literal dollar sign. $& inserts the whole match.
An empty string pattern inserts the replacement at the start of the string. For example "xxx".replace("", "_") returns "_xxx".
Did you know?
replaceAll() arrived much later (ES2021) because developers kept forgetting the g flag on replace(). Both APIs remain useful — replace for first-match and advanced regex, replaceAll for clear “change every copy” intent.