JavaScript String replaceAll() Method: Replacing All String Occurrences

The replaceAll() method in JavaScript is a powerful tool for replacing all occurrences of a substring or a regular expression pattern within a given string. Introduced in ECMAScript 2021, this method provides a more straightforward and efficient way to perform global replacements compared to using regular expressions with the g flag. This guide covers the syntax, usage, and practical examples of the replaceAll() method, providing you with a solid understanding of how to use it effectively in your JavaScript projects.

What is the replaceAll() Method?

The replaceAll() method allows you to replace all instances of a specified substring or regular expression pattern in a string with a new substring. Unlike the replace() method, which only replaces the first occurrence (or all occurrences when used with a global regular expression), replaceAll() directly handles global replacements without needing the g flag in regular expressions.

Purpose of the replaceAll() Method

The main purpose of the replaceAll() method is to:

  • Replace all occurrences of a substring with another substring.
  • Replace all matches of a regular expression pattern with a replacement string.
  • Provide a more readable and maintainable way to perform global string replacements.

Syntax of replaceAll()

The replaceAll() method takes two arguments:

string.replaceAll(searchValue, replacementValue);
Parameter Type Description
`searchValue` String | RegExp The substring or regular expression to be replaced. If a string is provided, it is treated as a literal string, and all occurrences of this string will be replaced. If a regular expression is provided, it must be a non-global regular expression; otherwise, a TypeError will be thrown.
`replacementValue` String | Function The string that replaces the `searchValue`. It can also be a function that returns the replacement string. If a function is used, it will be invoked for each match.

Return Value

The replaceAll() method returns a new string with all occurrences of the searchValue replaced by the replacementValue. The original string remains unchanged.

Examples of replaceAll() Usage

Let’s explore several examples to illustrate how the replaceAll() method works in different scenarios.

Replacing All Occurrences of a Substring

The simplest use case is to replace all occurrences of a specific substring within a string.

const originalString1 = "Hello world world world";
const newString1 = originalString1.replaceAll("world", "JavaScript");
console.log(newString1); // Output: Hello JavaScript JavaScript JavaScript

In this example, all instances of “world” are replaced with “JavaScript”.

Replacing with an Empty String

You can use replaceAll() to remove all occurrences of a substring by replacing it with an empty string.

const originalString2 = "Remove all spaces ";
const newString2 = originalString2.replaceAll(" ", "");
console.log(newString2); // Output: Removeallspaces

Here, all spaces are removed from the original string.

Using a Function for Replacement

The replacementValue can be a function that dynamically generates the replacement string based on the matched substring.

const originalString3 = "banana apple banana";
const newString3 = originalString3.replaceAll("banana", (match) => {
  return match.toUpperCase();
});
console.log(newString3); // Output: BANANA apple BANANA

In this example, each occurrence of “banana” is replaced with its uppercase version.

Replacing with Regular Expressions

The replaceAll() method can also be used with regular expressions. However, it’s important to note that the regular expression must not be global (i.e., it should not have the g flag).

const originalString4 = "The price is $20. The tax is $5.";
const newString4 = originalString4.replaceAll(/\$(\d+)/g, (match, amount) => {
  return `USD ${amount}`;
});
console.log(newString4); // Output: The price is USD 20. The tax is USD 5.

In this example, the regular expression /\$(\d+)/g matches dollar amounts. The replacement function formats these amounts with “USD”.

Note: If you attempt to use a global regular expression without the g flag, a TypeError will be thrown. Make sure your regular expressions are non-global when using replaceAll(). ⚠️

Case-Insensitive Replacement

To perform a case-insensitive replacement, you can use a regular expression with the i flag.

const originalString5 = "Hello hello Hello";
const newString5 = originalString5.replaceAll(/hello/gi, "Hi");
console.log(newString5); // Output: Hi Hi Hi

Here, the regular expression /hello/gi matches “hello” in a case-insensitive manner, and all occurrences are replaced with “Hi”.

Complex Replacement Example: Camel Case to Snake Case

Here’s a more complex example that converts a string from camel case to snake case using replaceAll() with a regular expression and a replacement function.

const camelCaseString = "camelCaseStringExample";
const snakeCaseString = camelCaseString.replaceAll(
  /([A-Z])/g,
  (match, letter) => {
    return "_" + letter.toLowerCase();
  }
);
console.log(snakeCaseString); // Output: camel_case_string_example

In this example, the regular expression /([A-Z])/g matches each uppercase letter in the camel case string. The replacement function converts each matched letter to lowercase and prepends an underscore.

Real-World Applications of replaceAll()

The replaceAll() method is useful in various scenarios, including:

  • Data Cleaning: Removing or replacing unwanted characters or patterns in user input or data from external sources.
  • Text Formatting: Converting text to different formats, such as changing case or adding separators.
  • Templating: Replacing placeholders in a template string with actual values.
  • Code Transformation: Modifying code snippets, such as converting variable names or updating syntax.

Use Case Example: Masking Sensitive Information

Consider a scenario where you need to mask sensitive information in a string, such as credit card numbers or API keys. The replaceAll() method can be used to replace specific parts of the string with a masking character.

function maskSensitiveData(data, sensitivePattern, maskChar = "*") {
  return data.replaceAll(sensitivePattern, (match) => {
    return maskChar.repeat(match.length);
  });
}

const apiKey = "YOUR_API_KEY_HERE";
const maskedApiKey = maskSensitiveData(apiKey, /YOUR_API_KEY/g);
console.log(maskedApiKey); // Output: ******************

const creditCardNumber = "1234-5678-9012-3456";
const maskedCreditCard = maskSensitiveData(creditCardNumber, /\d{4}(?!$)/g);
console.log(maskedCreditCard); // Output: ****-****-****-3456

This example demonstrates how to use the replaceAll() method to mask sensitive information. The maskSensitiveData function takes a string, a regular expression pattern, and a masking character as arguments. It replaces all matches of the pattern with a string of masking characters of the same length. The result is a string with the sensitive data replaced by asterisks, enhancing data privacy.

Browser Support

The replaceAll() method is supported in all modern web browsers.

Conclusion

The replaceAll() method in JavaScript is a versatile and efficient tool for replacing all occurrences of a substring or regular expression pattern within a string. It offers a more straightforward and readable way to perform global replacements compared to using regular expressions with the g flag. By understanding its syntax, usage, and practical applications, you can effectively use the replaceAll() method to manipulate strings in your JavaScript projects.