JavaScript 所有重複字取代

使用 replace()

#dog
#cat
//宣告字串
var str="I have a dog, I love all dog, dog is my best friend!"

//顯示原字串
document.querySelector("#dog").innerHTML=str;

//執行取代,g代表global search,找出所有dog
//反斜線\為抵銷特殊字元
//取代所有dog為cat
var strReplaced=str.replace(/dog/g, "cat");
//【/dog/g】等於new RegExp("dog", "g")
//所以也可以寫成
var strReplaced=str.replace(RegExp("dog", "g"), "cat");

//顯示取代後的成果
document.querySelector("#cat").innerHTML=strReplaced;

Display
所有的dog都被取代成cat了

Leave a Reply

Your email address will not be published. Required fields are marked *