JavaScript 的字串替換靠 replace(),但它預設只換第一個符合項,這讓許多人誤以為語言缺少全域替換的能力。其實只要正確使用正則的 g 旗標,或用原型擴充補上 replaceAll,問題就解決了。
stringObj.replace(rgExp, replaceText)
$$:插入一個 $ 字元$&:整個比對到的子字串$`:比對位置之前的字串$':比對位置之後的字串$n:第 n 個括號捕獲組(n 為 1~9);$nn 為 01~99
function ReplaceDemo() {
var ss = "The man hit the ball with the bat.\n"
+ "while the fielder caught the ball with the glove.";
var re = /The/g; // g 旗標讓它換掉所有符合項
return ss.replace(re, "A");
}
function ReplaceDemo() {
var ss = "The rain in Spain falls mainly in the plain.";
var re = /(\S+)(\s+)(\S+)/g;
return ss.replace(re, "$3$2$1"); // 每兩個單字互換位置
}
華氏轉攝氏,替換內容需要計算,因此用函式回傳:
function f2c(s) {
var test = /(\d+(\.\d*)?)F\b/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."));
函式會收到 m+3 個參數:第一個是比對到的子字串,接著 m 個是各捕獲組,倒數第二個是比對在原始字串中的位移量,最後一個是原始字串本身。
若環境不支援 String.prototype.replaceAll(ES2021 之前),可自行補上:
String.prototype.replaceAll = function (s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
};
這裡的 gm 分別代表 global(全部)與 multiLine(多行模式)。呼叫方式:
"abcabcabc".replaceAll("a", "ad"); // "adbcadbcadbc"
要注意兩個細節:第一,s1 若含正則特殊字元(如 . * ? 等)需先跳脫,否則會被當成萬用字元;第二,在瀏覽器地址欄快速驗證很方便,輸入 javascript:alert("abcabcabc".replace(/a/g,"ad")) 就能看到結果。ES2021 之後已可直接使用原生的 replaceAll(),且它接受字串參數而不需自行轉正則,是更安全的選擇。