JavaScript replaceAll: Complete Guide to Replacing All String Occurrences

Master the replaceAll() method for efficient bulk string replacement in modern JavaScript applications

What is replaceAll()?

The replaceAll() method is a String prototype method that returns a new string with all matches of a pattern replaced by a replacement. The original string remains unchanged, adhering to JavaScript's string immutability principle.

In modern web development, string manipulation is a fundamental operation that developers encounter daily. Whether you're sanitizing user input, formatting data, or transforming content for display, the ability to replace all occurrences of a substring efficiently is crucial. The JavaScript replaceAll() method provides a clean and performant solution for this common requirement.

Key Features

Simple Syntax

Straightforward API for replacing all substring occurrences without regex complexity

Pattern Support

Works with both plain strings and regular expressions with global flag

Function Replacements

Dynamic replacements using callback functions for complex transformations

Immutable

Returns a new string, leaving the original unmodified

Basic Syntax and Parameters

Syntax

str.replaceAll(pattern, replacement)

Parameters

  • pattern: Can be a string or a RegExp. If a string is passed, all exact matches are replaced. If a RegExp is used, it must have the global (g) flag set.
  • replacement: Can be a string or a function that returns the replacement value.

Return Value

Returns a new string with all matches replaced. The original string is never modified.

Code Examples

Basic String Replacement

The simplest use case involves replacing all occurrences of a substring with another string.

const originalText = "The quick brown fox jumps over the lazy dog. The dog is very lazy.";
const result = originalText.replaceAll("dog", "cat");
console.log(result);
// Output: "The quick brown fox jumps over the lazy cat. The cat is very lazy."

Using Regular Expressions

When you need pattern-based replacement, regular expressions provide flexibility. For more advanced pattern matching techniques, check our guide on regular expressions in JavaScript.

const text = "Hello hello HELLO world";
const result = text.replaceAll(/hello/gi, "Hi");
console.log(result);
// Output: "Hi Hi Hi world"

Replacement with Function

For dynamic replacements based on match context, pass a function as the replacement.

const prices = "Apples: $1, Oranges: $2, Bananas: $3";
const result = prices.replaceAll(/\$(\d+)/g, (match, number) => {
 const value = parseInt(number, 10);
 return `$${(value * 1.1).toFixed(2)}`;
});
console.log(result);
// Output: "Apples: $1.10, Oranges: $2.20, Bananas: $3.30"

Comparison with replace()

Key Differences

Aspectreplace()replaceAll()
ReplacesFirst occurrence onlyAll occurrences
Pattern requirementRegex requires global flagRegex must have global flag
Use caseSingle replacementBulk replacements
const text = "foo foo foo";

// Only replaces first occurrence
text.replace("foo", "bar"); // "bar foo foo"

// Replaces all occurrences
text.replaceAll("foo", "bar"); // "bar bar bar"

// Regex without global flag throws error
try {
 text.replaceAll(/foo/, "bar");
} catch (e) {
 console.log(e instanceof TypeError); // true
}

Understanding the difference between equality comparisons and string methods helps you write more predictable JavaScript code.

Alternative Approaches

split() and join() Method

Before replaceAll() was available, developers commonly used the split-join pattern. These complementary string methods are essential for any JavaScript developer to understand.

const text = "one two one three one";
const result = text.split(" ").join(", ");
// Output: "one, two, one, three, one"

// For substring replacement
const sentence = "The cat sat on the cat mat";
const replaced = sentence.split("cat").join("dog");
// Output: "The dog sat on the dog mat"

Regular Expression with replace()

Using new RegExp() with the global flag provides similar functionality.

const text = "apple APPLE Apple";
const searchTerm = "apple";
const regex = new RegExp(searchTerm, "gi");
const result = text.replace(regex, "fruit");
// Output: "fruit fruit fruit"

While Loop with includes()

For maximum control, a while loop can be used. This approach leverages closures to maintain state during iteration.

let text = "test test test";
while (text.includes("test")) {
 text = text.replace("test", "passed");
}
// Output: "passed passed passed"
Best Practices

Use replaceAll() for Simple Cases

For literal string replacement, prefer replaceAll() for cleaner, more readable code

Handle Edge Cases

Consider empty patterns and non-matching scenarios in your implementation

Functions for Complex Logic

Use callback functions when replacements depend on matched content

Validate User Input

Sanitize and validate replacement patterns from untrusted sources

Common Use Cases in Web Development

1. Sanitizing User Input

When building web applications, security is paramount. Use replaceAll() to sanitize user input and prevent XSS attacks.

function sanitizeInput(input) {
 const forbidden = ["<script>", "javascript:", "onerror="];
 let result = input;
 for (const term of forbidden) {
 result = result.replaceAll(term, "");
 }
 return result;
}

2. Formatting Display Data

function formatPhoneNumber(phone) {
 return phone.replaceAll(/[\s-()]/g, "");
}

formatPhoneNumber("(555) 123-4567"); // "5551234567"

3. URL Slug Generation

Create clean, SEO-friendly URLs by transforming titles into URL slugs. This is essential for SEO optimization of your web content.

function createSlug(title) {
 return title
 .toLowerCase()
 .replaceAll(/[^a-z0-9]+/g, "-")
 .replaceAll(/^-|$-$/g, "");
}

createSlug("Hello World! How Are You?"); // "hello-world-how-are-you"

Browser Compatibility

The replaceAll() method has been supported in modern browsers since August 2020.

BrowserVersionRelease Date
Chrome85+August 2020
Firefox77+May 2020
Safari13.1+March 2020
Edge85+August 2020

For projects supporting older browsers, consider using a transpiler like Babel or falling back to the split/join method.

Summary

The JavaScript replaceAll() method provides an elegant solution for replacing all occurrences of substrings or patterns in strings. Its introduction in ECMAScript 2021 simplified what previously required workarounds or regular expressions with global flags.

Key Takeaways

  • Use replaceAll() for simple substring replacement
  • Ensure regex patterns include the global flag
  • Leverage replacement functions for dynamic transformations
  • Consider browser compatibility for legacy support
  • Choose readability over micro-optimizations in most cases

Mastering these fundamental JavaScript string methods will make you a more effective web developer.

Need Help with JavaScript Development?

Our team of expert developers can help you build performant web applications using modern JavaScript techniques.