DIV CSS 佈局教程網

深入比較 JavaScript 的 exec 與 match 方法
編輯:關於JavaScript     

先分清楚誰是誰的方法

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"

這種情況下兩者等價。

加上 g 全域旗標後就不同了

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" 是括號內的分組。

match 在兩種條件下會等同 exec

  1. 正則中含有分組(括號)。
  2. 只會有一個比對結果(即沒有加 g)。
var str = "cat2,hat8";
var p = /c(at)\d/;
alert(p.exec(str));    // "cat2,at"
alert(str.match(p));   // "cat2,at"

這就是為什麼兩者有時看起來一模一樣。

總結對照

  • match:回傳所有比對組成的陣列,但必須指定 g;不指定 g 時只回傳一個元素的陣列,且該元素是完整比對(拿不到分組)。
  • exec:永遠回傳與「第一個比對」相關的資訊,陣列包含完整比對字串與所有分組的反向參照,可透過 lastIndex 反覆呼叫取得全部結果。

實務選擇:只想確認「有沒有」用 test();想一次取出全部比對字串用 match(/x/g);需要分組細節或要走訪全部比對則用 exec。ES6 之後若需要更完整的比對資訊(含位置、命名群組),可改用 matchAll()。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved