Replace all occurrences in a string with JavaScript

Sun, 02 April 2017

replaceAll.js
String.prototype.replaceAll = function(find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};

var myString = "When I was young I was young.";
myString = myString.replaceAll("I", "you");  // Replace all 'I' with 'you'
myString = myString.replaceAll("was", "were");  // Replace all 'was' with 'were'

alert(myString); // When you were young you were young