.replaceAll()
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):
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:
The following code won’t work because the regular expression search value is not global:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours