You may try this as an alternative of replace function

String.prototype.fakeReplace = function(str, newstr) {
    return this.split(str).join(newstr);
};

var str = "Welcome javascript";
str = str.fakeReplace('javascript', '');
alert(str); // Welcome

DEMO.

Answer from The Alpha on Stack Overflow
🌐
Dmitri Pavlutin
dmitripavlutin.com › replace-all-string-occurrences-javascript
3 Ways To Replace All String Occurrences in JavaScript
January 27, 2023 - You can replace all occurrences of a string using split and join approach, replace() with a regular expression and the new replaceAll() string method.
Discussions

javascript - How do I replace all occurrences of a string? - Stack Overflow
Given a string: string = "Test abc test test abc test test test abc test test abc"; This seems to only remove the first occurrence of abc in the string above: string = string.replace('ab... More on stackoverflow.com
🌐 stackoverflow.com
JavaScript String replace vs replaceAll - Stack Overflow
ECMAScript 2021 has added a new String function replaceAll. A long time ago in a galaxy not so far away, people used split + join or regular expressions to replace all occurences of a string. I cre... More on stackoverflow.com
🌐 stackoverflow.com
Isd there an Alternative to Replace() function in javascript - JavaScript - SitePoint Forums | Web Development & Design Community
Hello i am developing an advanced ebay store and listing and would like to use jquery with it. Now i want to stay well in ebays rules and use javascript that they have deamed safe. I know of 2 ways of bypassing there detection script to use code that they have banned but i dont want to do this ... More on sitepoint.com
🌐 sitepoint.com
0
December 7, 2011
Can i use replaceAll in javascript? - Stack Overflow
This is a simpler alternative: "Substitute X".replace(/X/g, "me"). Also more performant than split and join. See caniuse.com/mdn-javascript_grammar_regular_expression_literals. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 10543656 › alternative-to-jquery-replaceall
javascript - Alternative to jQuery replaceAll()? - Stack Overflow
before I tri.replaceAll, though with the setTimeout it happens after... So I guess my problem is that eP doesn't carry the datepicker state after it's been used in #nrow, just the html. FIXED! changed eP.appendTo to $('#eP').appendTo so that it takes it from the dom instead of the original variable. Oops! Thanks for making me re-think this with your just detach() comment! javascript ·
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).

🌐
Better Programming
betterprogramming.pub › javascript-string-replaceall-has-landed-in-all-major-browsers-9417e2f831d4
JavaScript: String.replaceAll has Landed in All Major Browsers | by Ozan Tunca | Better Programming
September 16, 2020 - With the most recent version of v8, we now have several new JavaScript features available in all major browsers — one of which is String.prototype.replaceAll. It is used for replacing all occurrences of a given string or a regular expression with another string. It looks like this: It is a very simple addition to String.prototype.replace. Being the micro-optimization geek that I am, I decided to take a look at how this new feature performs compared to its alternatives.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replace
String.prototype.replace() - JavaScript - MDN Web Docs
A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead.
🌐
Ozan Tunca
ozantunca.org › stringreplaceall-has-landed-on-all-major-browsers-should-we-refactor-yet
String.replaceAll has landed on all major browsers. Should we refactor yet?
September 6, 2020 - view raw replaceall example.js hosted with ❤ by GitHub · It is a very simple addition to String.prototype.replace that we already have. Being the micro-optimization geek that I am, I decided to take a look at how this new feature performs compared to its alternatives. The purpose of this article, therefore, is to showcase this new feature and encourage the readers to approach new features from a different perspective. Since the early days of JavaScript, the prototype of String provided us with a function called replace which in essence did the same thing as replaceAll but it replaces only the first occurrence of the searchValue.
Find elsewhere
🌐
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 - Replacing all occurrences of a string in JavaScript can be accomplished using several methods: Regular expressions with the global flag (g) provide flexibility and power. split and join offer a non-regex alternative.
Top answer
1 of 2
48

From gleaning the documentation for replaceAll, we find the following tidbits:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

Note: When using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

In other words, when calling replaceAll with a regex literal or RegExp, it must use the global flag. So, there doesn't seem to be much gained by calling replaceAll versus just using the current replace. However, one difference with replaceAll is that when passing it a string, it will automatically do a global replacement. This is where you might save yourself a bit of typing, by not having to enter a global flag.

2 of 2
1

There are performance and memory footprint differences between those methods. This might be important in low-level operations that are executed many times on your web page (such as general replacements done on page load). You can get away using replace function most of the time, but never use split/join.

Split-join

Split-join is very inefficient; never use it for replacements. It performs a search, creates an array (possibly very large), and then loops over the array to build a new string. Replacements should simply construct a new string directly.

// ❌ don't do this
console.log(source.split(str1).join(str2));

replaceAll(string) vs replace

Use replaceAll with a string when you can. The call to replaceAll(string, string) will be significantly faster than using a RegExp, as it's easier to optimize. Benchmarks show replaceAll is about 2x faster in Firefox 147 (even for very short strings). Also note that there is no point in compiling regular expressions when you only need to work with strings (new RegExp adds both object creation and parser overhead).

// ✅replaceAll(str) wins over ❌replace(re)
console.log(source.replace(new RegExp(str1,"g"), str2));
//versus
console.log(source.replaceAll(str1, str2));

On top of performance issues, if str1 contains special characters, you might get very unusual results:

// ❌ this will just be wrong; all this is part of a regexp: `[/, '').replace(/]`
'ab[c]'.replace(/[/, '').replace(/]/, ''); // -> b[c]
// ❌ `[` should be escaped and so you get: SyntaxError: unterminated character class.
'ab[c]'.replace(new RegExp('['), '').replace(new RegExp(']'), '')

replaceAll(RegExp) vs replace

When you want to use a regular expression, there is less of a difference between replaceAll and replace. In terms of performance, replace might actually be better, as it has been optimized over a longer period of time in browsers.

// replaceAll(re) ~= replace(re)
console.log(source.replace(regex, replacement));
//versus
console.log(source.replaceAll(regex, replacement));

Note however that it might be a good thing that 'abc'.replaceAll(/abc/, '') throws an error. If your intention is to replace all occurrences, it's very easy to make a mistake and forget the g modifier. So replace might fail silently, but replaceAll will let you know.

/** Replaces all occurrences of "ice" with "summer" */
function replaceIceWithSummer(text) {
    // ❌oh no we forgot g, ✅but replaceAll will remind us to replace all of ice
    return text.replaceAll(/ice/i, "summer");
}

That is even more important when the regexp is used in many places.

🌐
HackerNoon
hackernoon.com › 5-simple-ways-to-replace-all-string-occurrences-in-javascript
5 Simple Ways to Replace All String Occurrences in JavaScript | HackerNoon
March 7, 2023 - JavaScript has multiple methods for replacing strings, one of which is the String.prototype.replace() method.
🌐
Robin Wieruch
robinwieruch.de › javascript-replaceall
Replace all occurrences of a string in JavaScript - Robin Wieruch
June 2, 2020 - While replaceAll isn’t fully available yet, you can use the regex version of replaceAll and the global flag g with JavaScript’s replace version to replace all occurrences of a string.
🌐
GeeksforGeeks
geeksforgeeks.org › difference-between-stringprototypereplace-and-stringprototypereplaceall-in-javascript
Difference Between String.prototype.replace() and String.prototype.replaceAll() in JavaScript | GeeksforGeeks
July 11, 2024 - Both String.prototype.replace and String.prototype.replaceAll are powerful tools for the string manipulation in JavaScript. The replace is versatile for the various replacement needs while replaceAll offers a straightforward approach for the replacing all instances of a pattern.
🌐
Medium
medium.com › theburningmonk-com › javascript-string-replace-all-without-regex-caeb9fde17f6
Javascript — string replace all without Regex | by Yan Cui | theburningmonk.com | Medium
July 3, 2017 - One peculiar thing I find in Javascript is that String.replace only replaces the first instance of the substring, unless you use a Regex.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replaceAll
String.prototype.replaceAll() - JavaScript - MDN Web Docs
In this case the behavior of replaceAll() is entirely encoded by the [Symbol.replace]() method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).
🌐
SitePoint
sitepoint.com › javascript
Isd there an Alternative to Replace() function in javascript - JavaScript - SitePoint Forums | Web Development & Design Community
December 7, 2011 - Hello i am developing an advanced ebay store and listing and would like to use jquery with it. Now i want to stay well in ebays rules and use javascript that they have deamed safe. I know of 2 ways of bypassing there det…
🌐
Peterdaugaardrasmussen
peterdaugaardrasmussen.com › 2023 › 01 › 14 › javascript-string-replace-all
Javascript - string replace all using replaceAll
January 14, 2023 - Javascript - this posts shows how to use the built-in replaceAll to replace substrings or alternatives if you do not have support for replaceAll.
🌐
Alexanderkaran
blog.alexanderkaran.com › replace-vs-replace-all
Replace vs Replace All Comparison - Alexander Karan's Blog
October 19, 2024 - The fantastic function replaceAll has full support across all browsers except IE; you can find the full breakdown here.
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-replace-all-occurrences-of-a-string-in-JavaScript
How to replace all occurrences of a string in JavaScript?
November 7, 2022 - In JavaScript, there are several methods to replace all occurrences of a substring within a string. This tutorial covers three effective approaches: using split() and join(), regular expressions with replace(), and the modern replaceAll() method.
🌐
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 - If pattern is a regular expression, you need to include the g flag (where g stands for global) or replaceAll() will throw an exception - specifically, the error will be a TypeError.