JavaScript String replaceAll()

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.

Example

const message = "ball bat";

// replace all occurrence of b with c let result = message.replaceAll('b', 'c');
console.log(result); // Output: call cat

replaceAll() Syntax

The syntax of replaceAll() is:

str.replaceAll(pattern, replacement)

Here, str is a string.


replaceAll() Parameter

The replaceAll() method takes in:

  • pattern - either a substring or a regex that is to be replaced
  • replacement - the pattern is replaced with this replacement (can be either a string or a function)

replaceAll() Return Value

  • The replaceAll() method returns a new string, with all matches of a pattern replaced by a replacement.

Note: A RegExp without the global ("g") flag will throw a TypeError.


Example 1: Using replaceAll()

const text = "Java is awesome. Java is fun.";

// passing a string as the first parameter
let pattern = "Java"; let new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text); // passing a regex as the first parameter
pattern = /Java/g; new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text);

Output

JavaScript is awesome. JavaScript is fun
JavaScript is awesome. JavaScript is fun.

Replace Without Considering Uppercase/Lowercase

The replaceAll() method is case sensitive. To perform the case-insensitive replacement, you need to use a regex with a i switch (case-insensitive search).

Example 2: Case-Insensitive Replacement

const text = "javaSCRIPT JavaScript";

// all occurrences of javascript is replaced
let pattern = /javascript/gi; // case-insensitive and global search let new_text = text.replaceAll(pattern, "JS");
console.log(new_text); // JS JS

Output

JS JS

Example 3: Passing Function as a Replacement

You can also pass a function (instead of a string) as the second parameter to the replaceAll() method.

const text = "3.1415";

// generate a random digit between 0 and 9
function generateRandomDigit() {
  return Math.floor(Math.random() * 10);
}

// regex to match a digit
const pattern = /\d/g; const new_text = text.replaceAll(pattern, generateRandomDigit);
console.log(new_text);

Output

4.3518

You may get different output when you run this program. It's because the first digit in text is replaced with a random digit between 0 and 9.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community