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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replaceAll
String.prototype.replaceAll() - JavaScript - MDN Web Docs
This method does not mutate the string value it's called on. It returns a new string. Unlike replace(), this method replaces all occurrences of a string, not just the first one.
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).

Discussions

Best way to find and replace all instances if a string in an array of strings?
Currently I am doing this by iterating through each of the arrays and checking each value for the replaceable values and replacing the matches. That's pretty much what you'd need to do. map() is the method used for accomplishing this var arr = ["826", "7161", "", "", "x", "927", "hah", "hg7)", "x"] var arrWithClosed = arr.map(str => !str || str === "x" ? "Closed" : str) console.log(arrWithClosed) // 826, 7161, Closed, Closed, Closed, 927, hah, hg7), Closed More on reddit.com
🌐 r/learnjavascript
8
5
January 6, 2023
Replace all instances of variable name with other
after sources are indexed, right-click symbol, then select rename More on reddit.com
🌐 r/Xcode
9
2
January 21, 2022
how to find all occurrences of a word in a given sentence and replace it
You have to either parse the JSON via encoding/json (you can parse into map[string]any if you have dynamic content, then index into the map using the key you wish to mask and overwrite the value) then encode back to a []byte/string if you want to output json, or regexp replace the string (much more error-prone). Both options are relatively ugly just for logging, but they're about your options. More on reddit.com
🌐 r/golang
10
0
January 3, 2023
How do I replace all occurrences of a string?
Directly manipulating innerHTML will trigger a DOM repaint. I would advise replacing the attributes directly. if (document.querySelector('#pageRoot')){ document.querySelectorAll('a').forEach(function(a){ if(a.href.match(/example\.com/gi)){ a.href=''; } }); document.querySelectorAll('img').forEach(function(a){ if(a.src.match(/example\.com/gi)){ a.src=''; } }); } More on reddit.com
🌐 r/learnjavascript
1
1
September 7, 2020
🌐
CoreUI
coreui.io › blog › how-to-replace-all-occurrences-of-a-string-in-javascript
How to replace all occurrences of a string in JavaScript? · CoreUI
August 31, 2024 - In this example, the global regular expression /hello/g matches all instances of ‘hello’, ensuring that every occurrence is replaced with ‘hi’. This is one of the most common ways to replace multiple occurrences of a substring in JavaScript. When using a regular expression, special characters like . or * have special meanings. If your search string contains these characters, you’ll need to escape them using a backslash (\):
🌐
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:
🌐
Sentry
sentry.io › sentry answers › javascript › how do i replace all occurrences of a string in javascript?
JavaScript replaceAll: Replace All String Occurrences | 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.
🌐
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
🌐
Zipy
zipy.ai › blog › how-do-i-replace-all-occurrences-of-a-string-in-javascript
how do i replace all occurrences of a string in javascript
April 12, 2024 - The replaceAll() method is a new addition to JavaScript introduced in ES2021 (ECMAScript 2021). It provides a more straightforward way to replace all occurrences of a substring within a string, without the need for regular expressions.
🌐
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.
🌐
W3Schools
w3schools.com › jsref › jsref_string_replaceall.asp
JavaScript String replaceAll() Method
❮ Previous JavaScript String ... searches a string for a value or a regular expression. The replaceAll() method returns a new string with all values replaced....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-replace-all-occurrences-of-a-string-in-javascript
How to Replace All Occurrences of a String in JavaScript? - GeeksforGeeks
July 23, 2025 - To replace all occurrences of a string in JavaScript using a regular expression, we can use the regular expression with the global (g) Flag.
🌐
Flavio Copes
flaviocopes.com › home › javascript › how to replace all occurrences of a string in javascript
How to replace all occurrences of a string in JavaScript
July 2, 2018 - Dogs are great' const stripped = phrase.replaceAll('dog', '') stripped //"I love my ! Dogs are great" When you pass a plain string as the first argument, every occurrence is replaced.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replace
String.prototype.replace() - JavaScript - MDN Web Docs
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.
🌐
JavaScript Tutorial
javascripttutorial.net › home › how to replace all occurrences of a substring in a string
How To Replace All Occurrences of a Substring in a String in JavaScript
September 9, 2020 - "JavaScript will, JavaScript will, JavaScript will rock you!"Code language: JSON / JSON with Comments (json) The replaceAll() method replaces all occurrences of a substring in a string and returns the new string.
🌐
Designcise
designcise.com › web › tutorial › how-to-replace-all-occurrences-of-a-word-in-a-javascript-string
How to Replace All Occurrences of a Word in a JavaScript String? - Designcise
January 29, 2021 - Let's assume we have the following ... String.prototype.replaceAll() Introduced in ES12, the replaceAll() method returns a new string with all matches replaced by the specified replacement....
🌐
Programiz
programiz.com › javascript › examples › replace-occurence-string
JavaScript Program to Replace All Occurrences of a String
The replace() method takes the string that you want to replace as the first parameter and the string you want to replace with as the second parameter. // program to replace all occurrence of a string const string = 'Mr red has a red house and a red car'; const result = string.split('red')....
🌐
Codingem
codingem.com › home › how to replace all string occurrences in javascript (in 3 ways)
How to Replace All String Occurrences in JavaScript (in 3 Ways)
July 10, 2025 - To replace all string occurrences in JavaScript, use the replaceAll() method. Alternatively, you can use the split-join approach.
🌐
Mimo
mimo.org › glossary › javascript › replace
JavaScript Replace Method: Advanced String Manipulation
To replace all occurrences of a substring when using a regular expression, use the global flag (/g). For string literals, use the newer replaceAll() method instead.
🌐
Robin Wieruch
robinwieruch.de › javascript-replaceall
Replace all occurrences of a string in JavaScript - Robin Wieruch
June 2, 2020 - The first way uses a regular expression to find all matches with a global flag: ... const text = 'Hello World'; const newText = text.replace(/o/g, 'ö'); console.log(newText); // "Hellö Wörld" Without the global flag, the regex would only match one occurrence. An alternative to this is JavaScript’s replaceAll function, which is built-in for JavaScript string primitives, but not available for all browsers yet:
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › replace all occurrences of a string
Replace all occurrences of a string in JavaScript - 30 seconds of code
July 3, 2022 - Then, it can be passed to String.prototype.replace() to replace all occurrences of the string. The only issue here is that special characters need to be escaped, so that they are matched correctly.