The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.
Example
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 replacedreplacement- thepatternis replaced with thisreplacement(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()
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
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.
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.
Recommended Reading: JavaScript String replace()