正則表達式描述了一種字串匹配模式,可以檢查某個字串是否含有特定子串、把匹配到的部分做替換,或從字串中取出符合條件的片段。因為不常用,往往一陣子不用就忘,這裡把幾個核心函數的行徑整理清楚。
用法:RegExpObject.test(string)。若字串中含有匹配內容則返回 true,否則 false。這個方法很單純,對修飾符 g 沒有特殊處理。
var url = 'https://www.baidu.com?a=1&b=2&c=3'; console.log(/a=1/.test(url)); // true
用法:RegExpObject.exec(string)。返回一個存放匹配結果的陣列,找不到時返回 null。
exec() 比 test() 強大也複雜得多。找到匹配時返回的陣列中,第 0 项是整體匹配的文字,第 1 项起依序是各個子表達式的捕獲內容。此外陣列還帶兩個屬性:index 是匹配起始位置,input 是被檢索的原始字串。
關鍵差異在 g 修飾符:當正則帶有全域修飾符時,exec() 會從 lastIndex 指定的位置開始檢索;匹配成功後,它把 lastIndex 設為匹配結束的下一個位置,因此可以反覆呼叫來遍歷所有匹配。全部找完後返回 null,並把 lastIndex 重置為 0。
var url = 'https://www.baidu.com?a=1&b=2&c=3'; // 帶 g var reg = /([^?&=]+)=([^?&=])*/g; console.log(reg.exec(url)); // ["a=1", "a", "1", index: 21, ...] console.log(reg.exec(url)); // ["b=2", "b", "2", index: 25, ...] console.log(reg.exec(url)); // ["c=3", "c", "3", index: 29, ...] console.log(reg.exec(url)); // null reg.lastIndex = 0; // 重置後可重新遍歷 console.log(reg.exec(url)); // ["a=1", "a", "1", index: 21, ...]
若不帶 g,每次呼叫都從頭開始,永遠返回同一個結果,也不會推進 lastIndex。
用法:stringObject.match(regexp)。回傳值隨 g 修飾符而大不相同:
沒有 g:只找一次,返回類似 exec 的陣列,含捕獲組、index 與 input 屬性;找不到則返回 null。
var url = 'https://www.baidu.com?a=1&b=2&c=3'; var result = url.match(/([^?&=]+)=([^?&=])*/); console.log(result); // ["a=1", "a", "1", index: 21, input: "..."] console.log(result.index); // 21
有 g:執行全域檢索,返回的陣列只包含所有匹配到的整體字串,沒有捕獲組,也沒有 index 與 input。
var result = url.match(/([^?&=]+)=([^?&=])*/g); console.log(result); // ["a=1", "b=2", "c=3"] console.log(result.index); // undefined
這個差異是很多人踩過的坑:一旦加上 g,就別再指望能從 match 的結果裡取出子匹配。
用法:stringObject.replace(regexp/substr, replacement)。返回替換後的新字串(原字串不變)。帶 g 時替換所有匹配,否則只換第一個。
第二個參數可以是字串,也可以是函數。字串模式下 $ 有特殊含義:
$1、$2 … $99:對應第 1 到第 99 個子表達式匹配到的文字
$&:整個匹配到的子串
$`:匹配位置左側的文字
$':匹配位置右側的文字
$$:字面意义的 $ 符號
回調函數模式:參數依序為(整體匹配, 捕獲組1, 捕獲組2, …, 偏移量, 原始字串)。
var url = 'https://www.baidu.com?a=1&b=2&c=3';
// 不帶 g:只換一處
url.replace(/([^?&=]+)=([^?&=])*/, function (a, b, c, d, e) {
console.log(a, b, c, d, e);
// a=1 a 1 21 https://www.baidu.com?a=1&b=2&c=3
return 'ok';
});
// 結果:https://www.baidu.com?ok&b=2&c=3
// 帶 g:回調執行 3 次
url.replace(/([^?&=]+)=([^?&=])*/g, function () { return 'ok'; });
// 結果:https://www.baidu.com?ok&ok&ok
字串作為替換內容時的 $ 用法:
var url = 'https://www.baidu.com?a=1&b=2&c=3'; var reg = /([^?&=]+)=([^?&=])*/; // 不帶 g url.replace(reg, "$&"); // https://www.baidu.com?a=1&b=2&c=3 (原樣) url.replace(reg, "$1"); // https://www.baidu.com?a&b=2&c=3 url.replace(reg, "$2"); // https://www.baidu.com?1&b=2&c=3 url.replace(reg, "$'"); // https://www.baidu.com?&b=2&c=3&b=2&c=3 var regg = /([^?&=]+)=([^?&=])*/g; // 帶 g url.replace(regg, "$1"); // https://www.baidu.com?a&b&c url.replace(regg, "$2"); // https://www.baidu.com?1&2&3
實務上的選擇建議:只需要判斷「有沒有」用 test;需要位置資訊或逐個遍歷用 exec(記得處理 lastIndex,或乾脆用 matchAll 拿到迭代器);需要一次取出全部匹配用 match + g;替換場景優先考慮帶函數的 replace,因為它能拿到偏移量與捕獲組,比字串模式靈活得多。
最後提醒一個高頻 bug:反覆使用同一個帶 g 的正則物件去 test 或 exec,會因為 lastIndex 殘留而導致結果時對時錯。若只是臨時用一次,直接寫字面量 /pattern/g 讓它每次新建物件,或用 RegExp 建構式在函數內部建立,都能避開這個問題。