Skip to content

JavaScript string replace all | Example code

  • by

To replace all occurrences of a string in JavaScript use the string replaceAll() method defined by the ECMAScript 2021 language specification.

replaceAll(regexp, newSubstr)
replaceAll(regexp, replacerFunction)

JavaScript string replaces all

A simple example code replaces all “ABC” with “XYZ“.

<!DOCTYPE html>
<html>
<body>
  <script>
    var str = "1 ABC 2 ABC 3"
    let result = str.replaceAll("ABC", "XYZ");

    console.log(result)
  </script>

</body>
</html>

Output:

JavaScript string replace all

For older/legacy browsers:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

Regular Expression Based Implementation

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Split and Join (Functional) Implementation

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

Source: stackoverflow.com

Key Differences

  • replace() with RegExp: Uses a regular expression with the global flag to replace all occurrences.
  • replaceAll(): Directly replaces all occurrences of a substring without needing a regular expression.

Comment if you have any doubts or suggestions on this JS string replacement topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading