JavaScript 字符串replace全局替换

一般使用replace

let str = "2018-8-14";
str.replace('-','/')//2018/8-14

并没有替换第二个”-“,

所以我们用正则表达式重写一个

String.prototype.myReplace =

String.prototype.myReplace ||function(oldStr, newStr){//oldStr替换成newStr
let reg = new RegExp(oldStr, "g"); //创建正则RegExp对象 

return this.replace(reg, newStr);
}

str.myReplace('-','/');//2018/8/14

  

猜你喜欢

转载自www.cnblogs.com/detanx/p/jsReplaceg.html
今日推荐