.replaceAll()

Published Oct 9, 2023Updated Jan 31, 2024
Contribute to Docs

The .replaceAll() method returns a new string by replacing all the matches in a string of a given search value with a given replacement value.

Syntax

string.replaceAll(searchValue, replacementValue);

The searchValue can be either a string or RegExp.

Example

Replace all the occurrences of "scream" with "laugh":

const sentence = `I scream, you scream, we all scream for ice cream.`;
console.log(sentence.replaceAll('scream', 'laugh'));

This example results in the following output:

I laugh, you laugh, we all laugh for ice cream.

Codebyte Example

The first codebyte example uses .replaceAll() method to replace all occurrences of the lowercase letter “b” with the uppercase letter “B” in the string. It doesn’t use regular expressions (RegExp):

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

The second codebyte example replaces all occurrences of the letter “b” (case-sensitive) globally (all instances) with the uppercase letter “B” in the string, and it uses regular expressions (RegExp). Be careful that when using a regular expression search value, it must be global:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

The following code won’t work because the regular expression search value is not global:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy