JavaScript String replaceAll() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.replaceAll() returns a new string with every match of a pattern replaced (same API as MDN String.prototype.replaceAll()). Learn how it differs from replace(), why regexes must use the g flag, empty-string behavior, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

New string

03

String pattern

All matches

04

Regex

Must have g

05

Mutates?

No

06

Baseline

Widely available

Introduction

Want every copy of a word swapped — not just the first? replaceAll() is the clear tool for that. Pass a plain string and every occurrence is replaced. Pass a regex and it must include the g flag, or JavaScript throws TypeError.

Compared with replace(/pat/g, …), replaceAll("pat", …) is safer for literal text from users because characters like . and * are not treated as regex metacharacters.

💡
Beginner tip

replace("a", "b") → first "a" only.
replaceAll("a", "b") → every "a".

This page is part of JavaScript String Methods. Related topics include replace() and RegExp g flag.

Understanding the replaceAll() Method

str.replaceAll(pattern, replacement) searches for every match of pattern and returns a new string with those matches rewritten.

  • A string pattern replaces all occurrences.
  • A RegExp pattern must have the g flag.
  • Without g, replaceAll throws TypeError.
  • replacement may be a string or a function (same rules as replace).
  • The original string is never modified.

📝 Syntax

General form of String.prototype.replaceAll:

JavaScript
str.replaceAll(pattern, replacement)

Parameters

  • pattern — a string, or a RegExp that includes the g flag. Non-regex values are coerced to strings.
  • replacement — a string (may include $&, $1, …) or a function called for each match — same semantics as replace().

Return value

A string with all matches replaced:

SituationResult
String patternEvery occurrence replaced
Regex with gEvery match replaced
Regex without gThrows TypeError
No matchSame text (new string)
Empty string patternInserts between every code unit

Common patterns

JavaScript
"cat cat".replaceAll("cat", "dog");  // "dog dog"
"aabbcc".replaceAll("b", ".");       // "aa..cc"
"aabbcc".replaceAll(/b/g, ".");      // "aa..cc"

"xxx".replaceAll("", "_");           // "_x_x_x_"

⚡ Quick Reference

GoalCode
Replace every literalstr.replaceAll("old", "new")
Replace with regexstr.replaceAll(/old/g, "new")
First match onlystr.replace("old", "new")
Custom per matchstr.replaceAll(/pat/g, (m) => …)
Redact user text safelystr.replaceAll(name, "[REDACTED]")

🔍 At a Glance

Four facts to remember about String.replaceAll().

Returns
string

All matches swapped

String pattern
every match

Unlike replace()

Regex without g
TypeError

g is required

Mutates
no

Strings stay immutable

📋 replaceAll() vs replace()

replaceAll()replace()
String patternEvery occurrenceFirst occurrence only
Regex without gTypeErrorFirst match
Regex with gEvery matchEvery match
Best forClear “replace all”First swap / flexible regex
Literal user textSafer (no accidental regex)Risk if you wrap in RegExp

Examples Gallery

Examples follow MDN String.replaceAll() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Replace every match with a string or a global regex.

Example 1 — Basic replaceAll()

MDN demo: replace every "name", then every word-boundary is.

JavaScript
const paragraph = "This dog's name is just Dog! Yes, that is the name.";

paragraph.replaceAll("name", "nickname");
// "This dog's nickname is just Dog! Yes, that is the nickname."

paragraph.replaceAll(/\bis\b/g, "was");
// "This dog's name was just Dog! Yes, that was the name."
Try It Yourself

How It Works

Both "name" occurrences become "nickname". The global regex swaps both whole-word is matches for was.

Example 2 — Replace Every Character Match

MDN walkthrough: swap every "b" for a dot.

JavaScript
"aabbcc".replaceAll("b", ".");
// "aa..cc"

"aabbcc".replaceAll(/b/g, ".");
// "aa..cc"

"I love cats and cats!".replaceAll("cats", "dogs");
// "I love dogs and dogs!"
Try It Yourself

How It Works

A string pattern and a global regex both replace every match. Prefer the string form when you mean a literal substring.

📈 Practical Patterns

Errors, empty patterns, and safer redaction.

Example 3 — Non-Global Regex Throws

MDN note: regex patterns must include g.

JavaScript
try {
  "aabbcc".replaceAll(/b/, ".");
} catch (e) {
  e.name;  // "TypeError"
}

"aabbcc".replaceAll(/b/g, ".");
// "aa..cc"
Try It Yourself

How It Works

replaceAll insists on global regexes so “all matches” is always explicit. Add g, or use a plain string pattern instead.

Example 4 — Empty String Pattern

MDN behavior: insert the replacement between every code unit.

JavaScript
"xxx".replaceAll("", "_");
// "_x_x_x_"

"hi".replaceAll("", "-");
// "-h-i-"

// Contrast with replace (empty pattern prepends once):
"xxx".replace("", "_");
// "_xxx"
Try It Yourself

How It Works

Empty matches exist between characters (and at the ends). replaceAll fills all of them; replace only fills the start.

Example 5 — Safer Literal Redaction

MDN idea: string replaceAll avoids regex surprises in names.

JavaScript
function unsafeRedact(text, name) {
  return text.replace(new RegExp(name, "g"), "[REDACTED]");
}

function safeRedact(text, name) {
  return text.replaceAll(name, "[REDACTED]");
}

const report =
  "A hacker called ha.*er used special characters in their name.";

unsafeRedact(report, "ha.*er");
// "A [REDACTED]s in their name."  (.* ate too much!)

safeRedact(report, "ha.*er");
// "A hacker called [REDACTED] used special characters in their name."
Try It Yourself

How It Works

Building new RegExp(name, "g") treats .* as “any characters”. replaceAll(name, …) treats the name as plain text.

🚀 Common Use Cases

  • Bulk find-and-replace — swap every copy of a word or token.
  • Cleaning user text — remove or mask repeated substrings safely.
  • Template cleanup — replace placeholders that appear many times.
  • Global regex transforms — with an explicit g flag.
  • Not for first-only edits — use replace() when one swap is enough.
  • Not for reading matches — use match() / matchAll() to inspect hits.

🧠 How replaceAll() Builds the Result

1

Read pattern + replacement

Accept a string/RegExp pattern and a string or function replacement.

Input
2

Validate regex

If the pattern is a RegExp, require the g flag or throw TypeError.

Guard
3

Replace every match

Walk all matches and apply the replacement string or function.

Swap
4

Return a new string

The original str is unchanged.

📝 Notes

  • replaceAll with a string pattern replaces every occurrence.
  • A regex argument must include the g flag or a TypeError is thrown.
  • Empty string pattern inserts between every UTF-16 code unit.
  • Prefer string replaceAll for literal text that might contain regex characters.
  • Replacement strings support the same $ patterns as replace().
  • Always capture the return value — the original string does not update in place.

Browser & Runtime Support

String.prototype.replaceAll() is Baseline Widely available — supported across modern browsers since August 2020 (ES2021).

Baseline · Widely available

String.replaceAll()

Safe for modern production targets in browsers and runtimes (Node.js, Deno, Bun). Older engines may need a polyfill.

Modern Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
replaceAll() Excellent (modern)

Bottom line: Use String.replaceAll() when you want every match replaced. Remember: regex patterns require the g flag, and empty-string patterns insert between every character.

Conclusion

String.prototype.replaceAll() makes “change every occurrence” obvious — especially for plain string patterns. Use a global regex when you need pattern power, and keep replace() handy for first-only swaps.

Continue with replace(), RegExp g flag, or the String methods hub.

💡 Best Practices

✅ Do

  • Use replaceAll when every match should change
  • Pass a string pattern for literal user-controlled text
  • Include the g flag on every regex you pass in
  • Prefer replace when you only need the first match
  • Assign the return value to a new variable

❌ Don’t

  • Pass a non-global regex to replaceAll
  • Build new RegExp(userText, "g") without escaping
  • Forget empty-string patterns insert between characters
  • Expect the original string to change in place
  • Use replaceAll when a single swap is enough

Key Takeaways

Knowledge Unlocked

Five things to remember about String.replaceAll()

Replace every match — clearly and safely for literals.

5
Core concepts
🔎 02

String pattern

all matches

Rule
03

Regex needs

g flag

Guard
04

vs replace

all vs first

Compare
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.replaceAll(pattern, replacement) returns a new string where every match of pattern is swapped for replacement. Unlike replace() with a string pattern, it replaces all occurrences — not just the first.
No. Strings are immutable. replaceAll() returns a new string; the original stays the same.
replaceAll() throws TypeError. A regex pattern must include the global (g) flag.
Use replaceAll when you want every match — especially for plain string patterns. Use replace when you only want the first match, or when you already rely on replace’s first-match behavior.
Yes for literal text. Passing a string to replaceAll avoids accidentally treating characters like . * + as regex metacharacters (which can happen if you build new RegExp(userText, "g")).
An empty string pattern inserts the replacement between every UTF-16 code unit. For example "xxx".replaceAll("", "_") returns "_x_x_x_".
Did you know?

replaceAll() landed in ES2021 after years of developers writing split(old).join(new) or forgetting the g flag on replace(). The new method makes “all matches” the default intent.

More String Methods

Return to the hub for slice, trim, padStart, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful