Use the JavaScript replaceAll() method to replace all matches of a pattern in a given string. This method returns a new string with all matches of a pattern replaced by a replacement.
str.replaceAll(pattern, replacement)
The pattern
can be a string or a RegExp
, and the replacement
can be a string or a function to be called for each match.
JavaScript replaceAll() example
Simple example code.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const text = "Java is easy to code. Java is fun.";
let res = text.replaceAll("Java", "JavaScript");
console.log(res);
new_text = text.replaceAll(/Java/g, "JavaScript");
console.log(new_text);
</script>
</body>
</html>
Output:
Case-Insensitive Replacement
To perform the case-insensitive replacement, you need to use a regex with a i
switch (case-insensitive search).
const text = "javaSCRIPT JavaScript";
let pattern = /javascript/gi; // case-insensitive and global search
let new_text = text.replaceAll(pattern, "JS");
console.log(new_text); // JS JS
JavaScript String replace vs replaceAll
One difference with replaceAll
is that when passing it a string, it will automatically do a global replacement. This is where you might save yourself a bit of typing, by not having to enter a global flag.
Do comment if you have any doubts or suggestions on this JS method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version