exec 屬於正則表達式,參數是字串;match 屬於字串,參數是正則。
var re = /\d/;
re.exec("abc4def"); // 正確
"abc4def".match(/\d/); // 正確
兩者回傳的都是陣列(或 null)。
若正則中沒有括號分組,有比對到就回傳「只有一個元素」的陣列,該元素是比對到的第一段文字;沒有比對到則回傳 null。
var str = "cat,hat"; var p = /at/; // 注意:沒有 g alert(p.exec(str)); // "at" alert(str.match(p)); // "at"
這種情況下兩者等價。
var str = "cat,hat"; var p = /at/g; // 有 g alert(p.exec(str)); // "at" alert(str.match(p)); // "at,at"
差別的根源:exec 永遠只回傳第一個比對,而 match 在指定 g 的情況下會回傳所有比對。若想用 exec 取出全部結果,必須反覆呼叫直到回傳 null,並搭配 lastIndex。
var str = "cat,hat";
var p = /at/g;
var result, all = [];
while ((result = p.exec(str)) !== null) {
all.push(result[0]);
}
console.log(all); // ["at", "at"]
exec 回傳的陣列中,第一個元素是整段比對,之後依序是各個分組(反向參照)的內容:
var str = "cat2,hat8"; var p = /c(at)\d/; alert(p.exec(str)); // "cat2,at"
第一個元素 "cat2" 是完整比對,第二個 "at" 是括號內的分組。
var str = "cat2,hat8"; var p = /c(at)\d/; alert(p.exec(str)); // "cat2,at" alert(str.match(p)); // "cat2,at"
這就是為什麼兩者有時看起來一模一樣。
實務選擇:只想確認「有沒有」用 test();想一次取出全部比對字串用 match(/x/g);需要分組細節或要走訪全部比對則用 exec。ES6 之後若需要更完整的比對資訊(含位置、命名群組),可改用 matchAll()。