JavaScript Replace all Occurrences of a Substring in String

To replace all occurrences of a substring in a string with a new value in JavaScript, call replaceAll() method on this string, and pass the search string and replacement string as arguments.

Syntax

The syntax to replace all occurrences of a substring searchValue with a new value replaceValue in this string str is

str.replaceAll(searchValue, replaceValue)

replaceAll() method returns a new string with the replacements done, and keeps the original string str unchanged.

Examples

In the following example, we take three strings: str, searchValue, and replaceValue. We will use replaceAll() method to replace all the occurrence of searchValue with replaceValue in str.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var str = 'apple banana apple orange';
        var searchFor = 'apple';
        var replaceWith = 'mango';
        var result = str.replaceAll(searchFor, replaceWith);

        var output = '';
        output += 'Input String : ' + str;
        output += '\nOutput String: ' + result;
        document.getElementById('output').innerHTML = output;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to replace all the occurrences of a substring with a new value in this string in JavaScript, using replaceAll() method, with examples.