jsguides

String.prototype.replaceAll()

replaceAll(searchFor, replaceWith)

The replaceAll() method returns a new string with all occurrences of a specified value replaced. Introduced in ES2021, it solves a long-standing pain point: replacing every instance of a substring without needing a global regular expression.

Syntax

string.replaceAll(searchFor, replaceWith)

Parameters

  • searchFor — The value to search for. Can be a string or a global regular expression.
  • replaceWith — The value to replace matches with. Can be a string or a function.

String vs regex: the key difference

Before replaceAll(), replacing all occurrences required a global regex:

const text = "one one one";

// Using replace() with a string - only replaces first occurrence
text.replace("one", "X");
// "X one one"

// Using replace() with global regex - replaces all
text.replace(/one/g, "X");
// "X X X"

// Using replaceAll() with a string - replaces all directly
text.replaceAll("one", "X");
// "X X X"

This is the core advantage: replaceAll() lets you replace all occurrences using a plain string — no regex syntax required.

Global regex requirement

When using a regex with replaceAll(), it must be global (include the g flag). Non-global regexes will throw a TypeError:

const text = "a b a b a b";

// Valid: global regex works
text.replaceAll(/a/g, "X");
// "X b X b X b"

// Invalid: non-global regex throws TypeError
text.replaceAll(/a/, "X");
// TypeError: replaceAll must be called with a global RegExp

This safety check prevents a common bug where developers accidentally use a non-global regex expecting global replacement. The explicit global requirement makes the behavior of replaceAll() predictable — you can never mistakenly replace only the first match when you intended to replace all of them. Combined with the plain-string path, this gives you two clear routes to global replacement, each suited to a different kind of search pattern.

String immutability

Like all string methods, replaceAll() returns a new string — the original remains unchanged:

const original = "foo bar foo";
const result = original.replaceAll("foo", "baz");

console.log(original); // "foo bar foo" (unchanged)
console.log(result);    // "baz bar baz" (new string)

Because replaceAll() creates a new string, you can chain it with other string methods without worrying about mutating the original value. The examples below cover practical uses, from straightforward substring swaps to pattern-based replacement and data sanitization.

Examples

Basic string replacement

The simplest use case: replace all instances of a substring:

const message = "hello hello world";
console.log(message.replaceAll("hello", "hi"));
// "hi hi world"

const template = "{{name}} is {{age}} years old";
console.log(template.replaceAll("{{name}}", "Alice"));
// "Alice is {{age}} years old"

This direct string-to-string replacement is what makes replaceAll() convenient — you get global replacement without any regex syntax. When you need pattern matching rather than literal substring matching, pass a global regex instead.

Using a global regex for mass replacement

For complex patterns, use a global regex:

const text = "price: $10, $20, $30, $50";

// Remove all dollar amounts
const cleaned = text.replaceAll(/\$\d+/g, "$0");
console.log(cleaned);
// "price: $0, $0, $0, $0"

// Normalize whitespace
const messy = "a   b    c     d";
console.log(messy.replaceAll(/\s+/g, " "));
// "a b c d"

Regular expressions give you matching based on character classes, quantifiers, and alternation rather than fixed strings. The global flag tells replaceAll() to replace every match, just as it does when you pass a plain string. When the pattern you are replacing is a literal substring, stick with the simpler string-based call — it is clearer and avoids escaping headaches.

Data sanitization

replaceAll() is excellent for cleaning user-generated content:

function sanitizeInput(input) {
  return input
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll("&", "&amp;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#x27;");
}

const userComment = 'User says: <script>alert("xss")</script>';
console.log(sanitizeInput(userComment));
// "User says: &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"

// Another sanitization example: normalize line endings
const multiline = "line1\r\nline2\rline3\nline4";
console.log(multiline.replaceAll(/\r\n|\r|\n/g, "\n"));
// "line1\nline2\nline3\nline4"

When replaceAll() is the better choice

replaceAll() is the cleaner option when every occurrence should change and the pattern is a simple string. It avoids the ambiguity of replace() and removes the need to remember whether a global regular expression is required. That makes the code easier to scan and often easier to teach.

The method is especially useful for cleanup tasks such as normalizing punctuation, swapping tokens in templates, and sanitizing repeated substrings before display. Because the intent is explicit, readers do not have to wonder whether the first match is special.

Strings, regex, and safety

When you do use a regular expression, remember that replaceAll() insists on the global flag. That rule prevents accidental partial replacement. It also makes the difference between literal replacement and pattern replacement much more visible in the code.

For user-facing text, keep escaping and ordering in mind. If you are replacing multiple characters that can overlap, the order of operations can affect the result. A simple series of replacements is often fine, but complex sanitization may need a more deliberate approach.

When to Use replaceAll() vs replace()

ScenarioMethod
Replace all with string patternreplaceAll() (cleanest)
Replace all with complex patternreplaceAll(/pattern/g)
Replace first occurrence onlyreplace()
Replace with function callbackreplace() or replaceAll()

Key Behaviors

  • Returns a new string; original is unchanged
  • Replaces all occurrences by default
  • String search requires no regex syntax
  • Regex must include g flag (throws TypeError otherwise)
  • Works with replacement function as second argument

See Also