JavaScript 的字串替換靠 replace(),但它有個讓人踩坑的特性:不加正則的 g 旗標時,只會替換第一個符合項。本文完整說明參數、特殊匹配變數,並示範如何擴充出真正的 replaceAll。
stringObj.replace(rgExp, replaceText)
回傳值是完成替換後的「新」字串,原字串保持不變。
在替換文字中,你可以用下列特殊符號動態決定內容:
$$ 表示 $ 本身;$& 代表整個匹配到的片段;$` 代表匹配之前的內容;$' 代表匹配之後的內容;$n 與 $nn 則分別對應第 n、第 nn 個捕獲群組。
把字串中所有出現的 "The" 換成 "A":
function ReplaceDemo(){
var r, re;
var ss = "The man hit the ball with the bat.n";
ss += "while the fielder caught the ball with the glove.";
re = /The/g;
r = ss.replace(re, "A");
return(r);
}
利用 $1、$2、$3 可以把捕獲群組重新排列,例如把每一對單字的順序對調:
function ReplaceDemo(){
var r, re;
var ss = "The rain in Spain falls mainly in the plain.";
re = /(S+)(s+)(S+)/g;
r = ss.replace(re, "$3$2$1");
return(r);
}
華氏轉攝氏是函數型 replaceText 的經典應用。傳入類似 "Water boils at 212F" 的字串即可:
function f2c(s) {
var test = /(d+(.d*)?)Fb/g;
return(s.replace
(test,
function($0,$1,$2) {
return((($1-32) * 5/9) + "C");
}
)
);
}
document.write(f2c("Water freezes at 32F and boils at 212F."));
JavaScript 原生沒有 replaceAll,用迴圈跑又有效率疑慮,最乾淨的解法是掛到 String.prototype 上:
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
關鍵在 gm 兩個旗標:g 是 global(全域比對),m 是 multiLine(多行模式)。使用方式:string.replace(new RegExp(oldString,"gm"), newString)。
想快速驗證,直接在瀏覽器網址列輸入下面這行就能看結果:
javascript:alert("abcabcabc".replace(new RegExp("a","gm"),"ad"))
對照之下,若寫成 orgStr.replace(findStr, replaceStr),就只能換掉第一個符合項。順帶一提,ES2021 之後現代環境已原生支援 String.prototype.replaceAll,新專案可直接使用。