JavaScript Replace a Substring in String

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

Syntax

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

str.replace(searchValue, replaceValue)

replace() method returns a new string with the replacement(s) done, and keeps the original string str unchanged.

Examples

Replace the First Occurrence

In the following example, we take three strings: str, searchValue, and replaceValue. We will use replace() method to replace the first 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.replace(searchFor, replaceWith);

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

Replace All Occurrences using Global Modifier

In the following example, we take a string str and replace ‘apple’ with ‘mango’ at all the occurrences using global(g) modifier.

index.html

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

        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 a substring with a new value in this string in JavaScript, using replace() method, with examples.