JavaScript implementation of the string replaceAll function code sharing

  • 2020-05-24 05:13:23
  • OfStack

Since the replace function in javascript cannot replace all matched strings, we need to add a method for the String class. The code is as follows:


String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);  
     } else {  
        return this.replace(reallyDo, replaceWith);  
     }  
}


Related articles: