JS replace 替換全部數據


(1)使用具有全局標志g的正則表達式
var str = "dogdogdog";
var str2 = str.replace(/dog/g,"cat");//   
console.log(str2);
(2) 使用另一種具有全局標志g的正則表達式的定義方法
 var str='dogdogdog';
 var str2 = str.replace(new RegExp('dog','gm'),'cat'):
 console.log(str2);

(3) 給String 對象添加原型方法

String.prototype.replaceAll=function(str1,str2){
return this.replace(new RegExp(str1,'gm'),str2)
}
//調用
var str = "dogdogdog";
var str2 = str.replaceAll('dog','cat')
console.log(str2);

 


免責聲明!

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



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