Javascript String replaceAll(oldStr, newStr)

Description

Javascript String replaceAll(oldStr, newStr)


String.prototype.replaceAll = function(oldStr, newStr){
  let s = this.toString();
  if(oldStr instanceof RegExp){ let a = this.match(oldStr); oldStr = a === null ? '' : a[0]; }
  if(oldStr !== '') while(s.indexOf(oldStr) != -1){ s = s.replace(oldStr, newStr) }
  return s;// w  w  w. jav a 2  s  .  c  o m
};

Javascript String replaceAll(oldStr, newStr)

String.prototype.replaceAll = function(oldStr, newStr) {
 return this.split(oldStr).join(newStr);
};



PreviousNext

Related