As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

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

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

Here is how this answer evolved:

str = str.replace(/abc/g, '');

In response to comment "what's if 'abc' is passed as a variable?":

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

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

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

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

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
Answer from user21926 on Stack Overflow
Top answer
1 of 16
5259

As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

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

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

Here is how this answer evolved:

str = str.replace(/abc/g, '');

In response to comment "what's if 'abc' is passed as a variable?":

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

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

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

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

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

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

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.


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);
};

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

Check out this benchmark running these two implementations against each other.


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

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

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

🌐
Gitbook
olexsyn.gitbook.io › enote › progr › javascript › string › replaceall-polyfill
replaceAll() polyfill - ENote - GitBook
March 13, 2023 - /** * String.prototype.replaceAll() polyfill * https://gomakethings.com/how-to-replace-a-section-of-a-string-with-another-one-with-vanilla-js/ * @author Chris Ferdinandi * @license MIT */ if (!String.prototype.replaceAll) { String.prototype.replaceAll = function(str, newStr){ // If a regex pattern if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') { return this.replace(str, newStr); } // If a string return this.replace(new RegExp(str, 'g'), newStr); }; }
🌐
GitHub
github.com › vitejs › vite › issues › 7449
String.prototype.replaceAll polyfill is not included · Issue #7449 · vitejs/vite
March 25, 2022 - We use '@vitejs/plugin-legacy' to create legacy build and also include polyfills for our modern browsers. We use String.prototype.replaceAll method in our application, but we still miss its polyfill for the modern browsers, though our browserlist query includes modern browsers which do not ...
Author: vitejs
🌐
Stack Overflow
stackoverflow.com › questions › 38432849 › replace-all-with-java-matcher
regex - replace all with java matcher - Stack Overflow
July 18, 2016 - I'm trying to add hyperlink on stock information using JAVA matcher. For example, this string will be changed How do you think about Samsung and LG? I think Samsung is good. to How do you think...
🌐
X
x.com › _developit › status › 1097302964274892800
Jason Miller 🦊⚛ (@_developit) on X
February 18, 2019 - 🐣 110b String.prototype.replaceAll polyfill: https://t.co/vbPpAQEO3p
🌐
GeeksforGeeks
geeksforgeeks.org › java › matcher-replaceallstring-method-in-java-with-examples
Matcher replaceAll(String) method in Java with Examples - GeeksforGeeks
July 1, 2020 - // Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(FGF)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll(stringToBeReplaced)); } }
🌐
Maven Repository
mvnrepository.com › artifact › org.mvnpm › string.prototype.replaceall
Maven Repository: org.mvnpm » string.prototype.replaceall
Spec-compliant polyfill for String.prototype.replaceAll ESnext proposal · Central (1) Central · Atlassian External · Atlassian · WSO2 Releases · WSO2 Public · Hortonworks · JCenter · KtorEAP · Mulesoft · Sonatype · aar android apache api application arm assets build build-system bundle client clojure cloud config cran data database eclipse example extension framework github gradle groovy io ios javascript kotlin library logging maven mobile module npm osgi plugin resources rlang sdk server service spring sql starter testing tools ui war web webapp ·
🌐
Char0n
char0n.github.io › ramda-adjunct › 2.25.0 › replaceAll.js.html
replaceAll.js - Documentation
import { curryN, invoker } from ... = curryN(3, polyfill); export const replaceAllInvoker = invoker(2, 'replaceAll'); /** * Replaces all substring matches in a string with a replacement....
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replaceAll
String.prototype.replaceAll() - JavaScript - MDN Web Docs
The replaceAll() method of String values returns a new string with all matches of a pattern replaced by a 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. The original string is left unchanged.
🌐
Go Make Things
gomakethings.com › how-to-write-your-own-vanilla-js-polyfill
How to write your own vanilla JS polyfill | Go Make Things
Next, we need to create a function for the method we’re polyfilling, and setup some arguments. In this case, the replaceAll() method accepts two arguments: the substring to search for, and the string to replace it with.
Top answer
1 of 16
5258

As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

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

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

Here is how this answer evolved:

str = str.replace(/abc/g, '');

In response to comment "what's if 'abc' is passed as a variable?":

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

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

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

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

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

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

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.


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);
};

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

Check out this benchmark running these two implementations against each other.


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

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

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

🌐
GeeksforGeeks
geeksforgeeks.org › java › matcher-replaceallfunction-method-in-java-with-examples
Matcher replaceAll(Function) method in Java with Examples - GeeksforGeeks
September 7, 2021 - // Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(FGF)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println("Before Replacement: " + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "(GFG)"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll( x -> x.group().toLowerCase())); } }
🌐
Baeldung
baeldung.com › home › java › java string › java string.replaceall()
Java.String.replaceAll() | Baeldung
July 29, 2026 - The String class provides replace() and replaceAll(). The two methods look similar, and they can produce the same results sometimes: String input = "hello.java.hello.world"; String replaceResult = input.replace("hello", "hi"); assertEquals("hi.java.hi.world", replaceResult); String replaceAllResult = input.replaceAll("hello", "hi"); assertEquals("hi.java.hi.world", replaceAllResult);
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-replaceall-method
Java String replaceAll() Method - GeeksforGeeks
December 23, 2024 - public String replaceAll(String regex, String replace_str) ... Return Value: This method returns the resulting String. Example 2: Invalid regex when passed in raplaceAll() method, raises PatternSyntaxException. ... import java.io.*; class Geeks { public static void main(String[] args) { String str = "GFG"; // Incorrect Regular expression String regex = "\\"; // Passing null expression in // replaceAll method str = str.replaceAll(regex, " "); System.out.println(str); } }
🌐
GitHub
github.com › zloirock › core-js › issues › 900
String.prototype.replaceAll · Issue #900 · zloirock/core-js
December 27, 2020 - I'm using core-js@3.8.1 and I've noticed that String.prototype.replaceAll polyfill has a bug. It should support an algorithm defined by special replacements patterns. 'foo.bar'.replaceAll('.', '$$$$$'); This call actually returns foo$$$$$bar but it should return foo$$$bar instead.
Author: zloirock
🌐
Discourse
meta.discourse.org › contribute › bug
Discourse not loading on legacy browsers - Page 2 - Bug - Discourse Meta
March 25, 2022 - What about this @david if (!String.prototype.replaceAll) { String.prototype.replaceAll = function(str, newStr){ // If a regex pattern if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') { return this.replace(str, newStr); } // If a string return this.split(str).join(newStr); }; } I changed the string branch of the solution you shared, so it fixes converting Strings to Regex without escaping.
🌐
npm
npmjs.com › package › string-replace-all-ponyfill
string-replace-all-ponyfill - npm
December 17, 2020 - polyfill-library · es-shims · core-js · For automated tests, run npm run test:automated (append :watch for watcher support). MIT © Ivan Nikolić · string · replaceall · prototype · string.prototype.replaceall · ponyfill · npm i string-replace-all-ponyfill ·
      » npm install string-replace-all-ponyfill
    
Published: Dec 17, 2020
Version: 1.0.1