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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM