JavaScript `String.replaceAll()`

2 min read .

The String.replaceAll() method in JavaScript is a powerful tool for replacing all occurrences of a substring or pattern in a string. Unlike the traditional replace() method, which only replaces the first occurrence, replaceAll() efficiently replaces every match, making it a go-to choice for many developers.

What is String.replaceAll()?

String.replaceAll() is a method that replaces all occurrences of a specified substring or pattern within a string. It allows for both literal and regex-based replacements, providing more flexibility and control over string manipulation.

Syntax:

string.replaceAll(searchValue, replaceValue);
  • searchValue: The substring or regular expression pattern to search for in the string.
  • replaceValue: The substring to replace each occurrence of the searchValue.

How Does String.replaceAll() Work?

  • Literal Substring Replacement: When using a literal string for searchValue, replaceAll() replaces every exact match of that substring with replaceValue.
  • Regular Expression Replacement: If searchValue is a regex pattern, replaceAll() replaces all matches according to the pattern.

Examples of Using String.replaceAll()

  1. Basic Usage with a Literal Substring

Replace all occurrences of a word in a string:

const text = 'Hello World! Welcome to the World of JavaScript.';
const newText = text.replaceAll('World', 'Universe');

console.log(newText); 
// Output: "Hello Universe! Welcome to the Universe of JavaScript."
  1. Using replaceAll() with Regular Expressions

You can use regular expressions to replace patterns:

const text = 'The rain in Spain stays mainly in the plain.';
const newText = text.replaceAll(/ain/g, 'oon');

console.log(newText); 
// Output: "The roon in Spoon stays moolnly in the ploon."

Explanation:

  • /ain/g is a regex pattern that matches all occurrences of “ain”.
  • All matched substrings are replaced with “oon”.
  1. Replacing Special Characters

replaceAll() is useful for sanitizing or formatting strings by replacing special characters:

const unsafeString = 'Hello <world> & welcome!';
const safeString = unsafeString.replaceAll(/[<>&]/g, '');

console.log(safeString); 
// Output: "Hello world  welcome!"
  1. Using a Function as the Replacement

You can pass a function to dynamically generate the replacement value:

const text = 'apple, banana, cherry';
const result = text.replaceAll(/\b(\w+)/g, (match) => match.toUpperCase());

console.log(result); 
// Output: "APPLE, BANANA, CHERRY"

Explanation:

  • The function (match) => match.toUpperCase() is used to convert each match to uppercase.

Benefits of Using String.replaceAll()

  • Performance Efficiency: replaceAll() is optimized for replacing all occurrences, avoiding the need for complex loops.
  • Cleaner Code: It simplifies code by eliminating workarounds, such as using regex with the global flag (g) or chaining multiple replace() calls.
  • Enhanced Readability: Makes the intention of replacing all instances more explicit and clear.

When to Use String.replaceAll()?

  • Bulk Text Replacement: When you need to replace multiple occurrences of a substring or pattern.
  • Data Sanitization: For cleaning up user inputs, removing unwanted characters, or preparing strings for specific formats.
  • String Formatting: For reformatting strings or modifying content across an entire text.

Browser Compatibility

String.replaceAll() is supported in most modern browsers, including Chrome (version 85+), Firefox (version 77+), Safari (version 13.1+), and Edge (version 85+). However, it may not be supported in older browsers, such as Internet Explorer. If compatibility is an issue, consider using polyfills or alternative methods.

Conclusion

The String.replaceAll() method in JavaScript is a versatile and efficient way to replace all instances of a substring or pattern in a string. Whether you’re working with simple text or complex patterns, replaceAll() offers a straightforward solution for manipulating strings.

See Also

chevron-up