NeuroAgent

How to Replace All String Occurrences in JavaScript

Learn how to replace all occurrences of a string in JavaScript using replaceAll() method or regex. Complete guide with examples and browser compatibility info.

Question

How do I replace all occurrences of a string in JavaScript?

Given a string:

javascript
string = "Test abc test test abc test test test abc test test abc";

The basic replace() method only removes the first occurrence of “abc” in the string above:

javascript
string = string.replace('abc', '');

How can I replace ALL occurrences of “abc” in the string?

NeuroAgent

To replace all occurrences of a string in JavaScript, you can use either the modern replaceAll() method or the traditional approach with replace() combined with a regular expression using the global flag (/g). The replaceAll() method is the simplest solution, while the regex approach works in older browser versions.


Contents


Understanding the Problem with replace()

The basic replace() method in JavaScript only replaces the first occurrence of a substring, as you’ve discovered:

javascript
const string = "Test abc test test abc test test test abc test test abc";
const result = string.replace('abc', '');
console.log(result);
// Output: "Test  test test abc test test test abc test test abc"

This limitation has been a common source of confusion for JavaScript developers for many years [source]. The replace() method was designed to replace only the first match when given a string pattern, unless you explicitly specify otherwise [source].


Method 1: Using replaceAll()

The replaceAll() method is the modern, straightforward solution for replacing all occurrences of a substring [source].

Basic Usage

javascript
const string = "Test abc test test abc test test test abc test test abc";
const result = string.replaceAll('abc', '');
console.log(result);
// Output: "Test  test test  test test test  test test "

Key Features

  • Global replacement by default: When given a string pattern, replaceAll() automatically replaces all occurrences [source]
  • Flexible pattern types: Accepts both strings and regular expressions as patterns
  • Function support: Can accept a replacement function for dynamic replacements
  • Immutable operation: Returns a new string without modifying the original [source]

With Regular Expressions

When using regex with replaceAll(), you must include the global flag (/g), otherwise it will throw a TypeError [source]:

javascript
// Correct usage with global flag
const result = string.replaceAll(/abc/g, '');

// This will throw an error:
// TypeError: replaceAll must be called with a global RegExp
const errorResult = string.replaceAll(/abc/, '');

Method 2: Using replace() with Global Regex

For environments that don’t support replaceAll(), you can use the traditional approach with replace() and a regular expression with the global flag [source].

Basic Usage

javascript
const string = "Test abc test test abc test test test abc test test abc";
const result = string.replace(/abc/g, '');
console.log(result);
// Output: "Test  test test  test test test  test test "

Key Features

  • Universal compatibility: Works in all JavaScript environments
  • Explicit global flag: Clear intent with the /g flag
  • Same functionality: Identical results to replaceAll() when used correctly

Why the /g Flag is Required

The global flag (/g) tells the regular expression engine to find all matches in the string rather than stopping after the first match [source]. Without it, replace() will behave exactly like the basic string replacement method.


Method 3: Alternative Approaches

Split and Join Method

You can also achieve global replacement by splitting the string and joining it with the replacement [source]:

javascript
const string = "Test abc test test abc test test test abc test test abc";
const result = string.split('abc').join('');
console.log(result);
// Output: "Test  test test  test test test  test test "

When to Use This Method

  • Very simple patterns: Works well for straightforward substring replacement
  • No regex complexity: Avoids regular expression syntax
  • Legacy environments: Works in very old JavaScript environments

However, this method is generally less efficient than the regex-based approaches [source].


Performance Comparison

Benchmark Results

According to various performance tests [source][source]:

  1. replaceAll() and regex replace() show negligible performance differences
  2. Split and join is typically slower for most use cases
  3. Performance becomes noticeable only with very large strings (10,000+ characters)

Performance Example

javascript
// Large string for performance testing
const largeString = 'abc'.repeat(10000);
const startTime = performance.now();

// Test replaceAll
const result1 = largeString.replaceAll('abc', 'xyz');
const endTime1 = performance.now();

// Test regex replace
const result2 = largeString.replace(/abc/g, 'xyz');
const endTime2 = performance.now();

console.log(`replaceAll: ${endTime1 - startTime}ms`);
console.log(`regex replace: ${endTime2 - endTime1}ms`);

“The speed difference between them is negligible. You have to be parsing large strings before even getting close to a 0.01 millisecond difference in speed.” [source]


Browser Compatibility

replaceAll() Support

The replaceAll() method is supported in:

  • Chrome 85+ (August 2020)
  • Firefox 77+ (June 2020)
  • Safari 13.1+ (March 2020)
  • Edge 85+ (August 2020) [source]

Polyfill for Older Browsers

If you need to support older browsers, you can add a polyfill [source]:

javascript
if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function(pattern, replacement) {
    return this.replace(new RegExp(pattern, 'g'), replacement);
  };
}

Feature Detection

Always check for method availability before using it [source]:

javascript
if (typeof String.prototype.replaceAll === 'function') {
  // Use replaceAll
  return string.replaceAll('abc', '');
} else {
  // Fallback to regex replace
  return string.replace(/abc/g, '');
}

Practical Examples

Example 1: Simple Text Replacement

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

Example 2: Case-Insensitive Replacement

javascript
const text = "ABC abc ABC abc";
const result = text.replace(/abc/gi, '');
console.log(result);
// Output: "    "

Example 3: Using Replacement Function

javascript
const text = "a1 b2 c3 d4";
const result = text.replace(/\d/g, (match) => {
  return parseInt(match) * 2;
});
console.log(result);
// Output: "a2 b4 c6 d8"

Example 4: Multiple Different Replacements

javascript
const text = "Hello world, hello JavaScript, hello programming";
const result = text.replace(/hello/gi, 'Hi');
console.log(result);
// Output: "Hi world, Hi JavaScript, Hi programming"

Best Practices

1. Choose the Right Method

  • Use replaceAll(): For modern codebases and maximum readability
  • Use regex replace(): For older browser support or when you need regex features
  • Use split/join: For very simple cases where regex isn’t needed

2. Always Test Edge Cases

javascript
// Test empty strings
const emptyResult = "abc".replaceAll('abc', ''); // Works fine
const emptyResult2 = "".replaceAll('abc', '');   // Also works

// Test no matches
const noMatch = "hello".replaceAll('abc', 'xyz'); // Returns original string

3. Consider Performance for Large Strings

javascript
// For very large strings, consider performance
function safeReplaceAll(str, pattern, replacement) {
  if (str.length > 10000) {
    return str.split(pattern).join(replacement);
  }
  return str.replaceAll(pattern, replacement);
}

4. Document Your Choice

javascript
/**
 * Replaces all occurrences of a substring in a string.
 * Uses replaceAll() for modern browsers, falls back to regex replace for compatibility.
 */
function globalReplace(str, search, replace) {
  if (typeof String.prototype.replaceAll === 'function') {
    return str.replaceAll(search, replace);
  }
  return str.replace(new RegExp(search, 'g'), replace);
}

Conclusion

Replacing all occurrences of a string in JavaScript is straightforward once you understand the available methods:

  1. Modern approach: Use replaceAll() for clean, readable code that automatically handles global replacement
  2. Traditional approach: Use replace() with /g flag for maximum browser compatibility
  3. Simple cases: Consider split/join for very basic replacement needs

The replaceAll() method is now widely supported across all major browsers and should be your default choice for new projects [source]. For legacy codebases, the regex approach provides equivalent functionality with broader compatibility.

Remember to consider your target audience’s browser support and performance requirements when choosing between these methods, and always test your implementation thoroughly.


Sources

  1. String.prototype.replaceAll() - JavaScript | MDN
  2. How do I replace all occurrences of a string? - Stack Overflow
  3. 3 Ways To Replace All String Occurrences in JavaScript - Dmitri Pavlutin
  4. How to replace all occurrences of a string in JavaScript? - CoreUI
  5. String.prototype.replaceAll · V8
  6. JavaScript replaceAll() – Replace All Instances of a String in JS - freeCodeCamp
  7. Benchmark: replaceAll vs regex replace - MeasureThat.net
  8. Replace vs Replace All Comparison - Alexander Karan