Here's a helper function that's a part of my utility library that I add into every piece of code that I write. Feel free to use it any way you like.
String.prototype.replaceAll = function (stringFind, stringReplace) {
var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
return this.replace(ex, stringReplace);
};
It adds a replaceAll
function to all strings so you don't have to constantly use RegEx throughout your code.
You can use it like this
str.replaceAll("$", "€");
Here's an example:
String.prototype.replaceAll = function (stringFind, stringReplace) {
var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
return this.replace(ex, stringReplace);
};
var str = "Win $50 and Get $100";
document.body.innerHTML = str.replaceAll("$", "€");
EDIT Test cases per comment below:
String.prototype.replaceAll = function (stringFind, stringReplace) {
var ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g");
return this.replace(ex, stringReplace);
};
var str = "test test abc test abc $%& test $%& $%&. test. abc $%& . .";
document.body.innerHTML = str + "<br />";
document.body.innerHTML += str.replaceAll(".", "") + "<br />";
document.body.innerHTML += str.replaceAll("%&", "") + "<br />";
document.body.innerHTML += str.replaceAll("test", "") + "<br />";
document.body.innerHTML += str.replaceAll("a-z", "") + "<br />";
Update
Per the comments from Danilo below (Thank you!), the original function would not allow for certain special characters, and would misbehave if a text range was entered into the replaceAll()
function. In my own code, I had not come across these cases as of yet.
Per this answer, I have updated my function so that it now escapes the RegEx to be more efficient in the provided test case scenarios.