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
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).

๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_string_replaceall.asp
JavaScript String replaceAll() Method
The replaceAll() method returns a new string with all values replaced. The replaceAll() method does not change the original string. The replaceAll() method was introduced in JavaScript 2021.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how do i replace all occurrences of a string in javascript?
How do I Replace all Occurrences of a String in JavaScript? | Sentry
You can also replace all occurrences of a string by first passing in the substring to be replaced in the split() method and then using the join() method to join the returned array with the new substring.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ replaceAll
String.prototype.replaceAll() - JavaScript | MDN
Unlike replace(), this method replaces all occurrences of a string, not just the first one. While it is also possible to use replace() with a global regex dynamically constructed with RegExp() to replace all instances of a string, this can have unintended consequences if the string contains ...
๐ŸŒ
Crio
crio.do โ€บ blog โ€บ how-to-replace-all-occurrences-of-a-string-in-javascript-2024-criodo
How Do I Replace All Occurrences of a String in JavaScript?
December 9, 2024 - var string = "Test abc test test abc test test test abc test test abc"; string = string.replace("abc", ""); console.log(string); // Output: "Test test test abc test test test abc test test abc" In this case, only the first "abc" is removed. To replace all occurrences, JavaScript offers several solutions:
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ replace-all-string-occurrences-javascript
3 Ways To Replace All String Occurrences in JavaScript
January 27, 2023 - In this post, you'll learn how to replace all string occurrences in JavaScript by splitting and joining a string, string.replace() combined with a global regular expression, and string.replaceAll().
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-replaceall-replace-all-instances-of-a-string-in-js
JavaScript replaceAll() โ€“ Replace All Instances of a String in JS
July 28, 2022 - The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.
Find elsewhere
๐ŸŒ
Alexanderkaran
blog.alexanderkaran.com โ€บ replace-vs-replace-all
Replace vs Replace All Comparison
October 21, 2024 - Learn how `replace` and `replaceAll` functions differ, and discover the benefits of using `replaceAll` for global string replacements
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ replace
String.prototype.replace() - JavaScript | MDN
The following script switches the words in the string. For the replacement text, the script uses capturing groups and the $1 and $2 replacement patterns. ... const re = /(\w+)\s(\w+)/; const str = "Maria Cruz"; const newStr = str.replace(re, "$2, $1"); console.log(newStr); // Cruz, Maria ยท This logs 'Cruz, Maria'. In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ javascript โ€บ replace
JavaScript Replace Method: Advanced String Manipulation
The replaceAll() method, introduced in ES12 (2021), replaces all occurrences of a substring without needing regular expressions.
๐ŸŒ
DEV Community
dev.to โ€บ maafaishal โ€บ javascript-stringreplace-useful-cases-3963
JavaScript `string.replace()` useful cases - DEV Community
September 24, 2024 - Replace all occurrences of a substring, use the global (g) flag with regular expression. let str = "Hello world, world!"; let result = str.replace(/world/g, "JavaScript"); // Output: "Hello JavaScript, JavaScript!"
๐ŸŒ
Hellonitish
hellonitish.com โ€บ blog โ€บ replace-all-occurrences-of-a-string-in-javascript
Hello Nitish โ€ข Replace all Occurrences of a String in JavaScript
Since String.replace() does not replace all the occurrences of a simple substring inside another string. You can pass the word or substring as a regular expression with the g flag attached to it. This way the string will replace all occurrences of the given word or substring.
๐ŸŒ
Medium
medium.com โ€บ @python-javascript-php-html-css โ€บ how-to-replace-a-string-in-javascript-everywhere-it-occurs-7fb58dd6910d
How to Replace a String in JavaScript Everywhere It Occurs
September 17, 2024 - Unlike replace(), which replaces only the first occurrence unless a global regular expression is used, replaceAll() replaces all occurrences directly. This method simplifies code and improves readability, especially for developers who might ...
๐ŸŒ
Pierremary
pierremary.com โ€บ en โ€บ posts โ€บ remove-all-whitespacefrom-a-string-in-javascript
The Best Way to Replace All String Occurrences in JavaScript
October 21, 2019 - The brut force approach to replace all occurrences is to split the string into chunks by the search string and join them back, adding the replacement string in between.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-replace-all-occurrences-of-a-string-in-javascript
How to replace all occurrences of a string in JavaScript?
The replace() method with a global regular expression flag (g) finds and replaces all occurrences of the pattern. const given_string = "original string"; const to_replace = new RegExp(to_replace_string, 'g'); const replacement = "replacement ...
๐ŸŒ
DEV Community
dev.to โ€บ iamcymentho โ€บ replacing-all-occurrences-of-a-string-in-javascript-a-comprehensive-guide-3o9n
Replacing All Occurrences of a String in JavaScript: A Comprehensive Guide - DEV Community
October 4, 2023 - String manipulation is a common task in JavaScript, and replacing all occurrences of a string is one such operation. In this comprehensive guide, we'll explore various techniques and methods to replace all instances of a substring within a string.
๐ŸŒ
DEV Community
dev.to โ€บ iamvictor โ€บ replace-occurrences-of-a-string-in-javascript-1clo
Replace Occurrences of a String in JavaScript - DEV Community
November 13, 2021 - The String type provides two methods ... with replacement, also accepts regular expressions, and uses the g flag to replace all occurrences of the substring with a new one....
๐ŸŒ
CoreUI
coreui.io โ€บ answers โ€บ how-to-replace-all-occurrences-in-a-string-in-javascript
How to replace all occurrences in a string in JavaScript ยท CoreUI
May 18, 2026 - The replaceAll() method searches the entire string for every occurrence of the first parameter and replaces each instance with the second parameter.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ examples โ€บ replace-all-occurrences-of-a-string
JavaScript Program to Replace All Occurrences of a String | Vultr Docs
December 19, 2024 - The i flag makes the pattern case-insensitive. Introduced in ECMAScript 2021, the replaceAll() method offers a straightforward way to replace all occurrences without needing to use a regular expression.
๐ŸŒ
Futurestud.io
futurestud.io โ€บ tutorials โ€บ node-js-string-replace-all-appearances
Node.js โ€” String Replace All Appearances
May 16, 2019 - Pass it in as the first argument to string.replace(): const string = 'e851e2fa-4f00-4609-9dd2-9b3794c59619' console.log(string.replace(/-/g, '')) // -> e851e2fa4f0046099dd29b3794c59619 ยท As you can see, using a string as the substring to search for will only replace the first appearance. A regular expression with the /g suffix replaces all dashes with an empty string. You should create a RegEx when using dynamic values as the search string. JavaScript provides a RegExp class to create a regular expression based on your variables: