閱讀 Qwrap 的原始碼時,在 stringHelper 裡看到這麼一段:
format: function (s, arg0) {
var args = arguments;
return s.replace(/\{(\d+)\}/ig, function (a, b) {
return args[(b | 0) + 1] || '';
});
}
用法是:
alert(format("{0} love {1}.", 'I', 'You')); // I love you
它的實作核心,就是String物件的 replace 方法——回傳一個根據正則表達式完成文字替換後的新字串(原字串不變)。以下由淺入深說明它的幾種用法。
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; // 建立正則模式,g 表示全域比對
r = ss.replace(re, "A"); // 用 "A" 替換所有 "The"
return r;
}
// 結果:A man hit the ball with the bat. while the fielder caught the ball with the glove.
若不加 g 旗標,只會替換第一個符合的片段,這是最常被忽略的細節。
替換字串中可以用 $n 語法引用正則裡括號捕獲的內容,做出「重新排列」的效果:
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;
}
// 結果:rain The Spain in mainly falls the in plain.
比對到的片段依次是 The rain、in Spain、falls mainly、in the,執行替換後完成了單詞位置的交換。對應關係為:
$1 → 第一個 (\S+)$2 → (\s+)$3 → 第二個 (\S+)當替換規則不是固定字串,而需要依比對內容動態計算時,就把函式當成第二個參數:
function f2c(s) {
var test = /(\d+(\.\d*)?)F\b/g;
return s.replace(test, function ($0, $1, $2) {
return (($1 - 32)) + "C";
});
}
f2c("Water boils at 212F 3F .2F 2.2F .2");
// 結果:Water boils at 180C -29C .-30C -29.8C .2
函式收到的參數依序為:
$0:整個比對到的片段,如 212F、3F、.2F、2.2F$1:第一個捕獲群組,即數值部分,如 212、3、.2、2.2$2:第二個捕獲群組,即小數部分最後的 .2 因為沒有 F 後綴,不符合比對條件,所以原樣保留。
回到開頭那段 format 函式,它的巧妙之處正在於用這個機制:正則 \{(\d+)\} 捕獲花括號裡的數字 b,再用 b | 0 把字串強制轉為整數(同時順便過濾掉非數字情況),最後從 arguments 中取出對應位置的參數回傳。這樣就完成了一個簡短實用的字串模板引擎。
g:全域比對,替換所有符合項而非僅第一個i:忽略大小寫m:多行模式,讓 ^ 與 $ 能比對每一行的起訖此外,若替換字串中需要出現真正的 $ 字面意義,要寫成 $$;而 $& 代表整個比對片段、$` 代表比對前的部分、$' 代表比對後的部分,這些都是實務上很實用的語法。