Skip to content

JavaScript string replace all | Example code

  • by

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

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

JavaScript string replace all

Simple example code replace 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

Do comment if you have any doubts or suggestions on this Js string replace 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

Your email address will not be published. Required fields are marked *