網站搜尋

javascript - 是較建議在 RegExp 物件上使用方法還是在 String 物件上使用方法?


在 Javascript 中,RegExp 物件和 String 物件上都有正則表達式匹配的方法。

RegExp 物件有這些方法

  • 執行
  • 測試

String 物件有這些方法

  • 比賽
  • 搜索

exec 和 match 方法非常相似:

/word/.exec("words");
//Result: ["word"]
"words".match(/word/);
//Result: ["word"]

/word/.exec("No match");
//Result: null
"No match".match(/word/);
//Result: null

/word/g.exec("word word");
//Result: ["word"]
"word word".match(/word/g);
//Result: ["word", "word"]

而 test 和 search 也非常相似:

/word/.test("words");
//Result: true
"words".search(/word/);
//Result: 0
//Which can converted to a boolean:
"word".search(/word/) > -1;
//Result: true

/word/.test("No match");
//Result: false
"No match".search(/word/) > -1;
//Result: false

在 RegExp 物件或 String 物件上使用這些方法,有沒有偏好?

答案#1

主要是個人偏好

這主要是個人偏好,雖然在功能上有些微差異(差異請參見最後一段)。除非你想開始進行效能測試並將問題變成關於效能的問題,否則這主要還是個人偏好。

我比較喜歡做:

string.match(/word/)

因為我認為這樣會讓程式碼的讀法像我的大腦思考這個操作的方式。我正在操作字串物件,並在其中尋找特定的正則表達式。對我來說,在字串中尋找某些東西作為字串物件的方法是合理的。對我而言,這讀起來像這樣:

object.action(tool)

我認為這就是物件導向程式碼應該運作的方式。

如果你有:

/word/.match(string)

那對我來說感覺像是:

tool.action(object)

我覺得這樣不太符合邏輯,也不太面向物件。是的,/word/ 技術上也是一個物件,但它不是我想要操作的那個物件,我更把它看作是我和我的物件一起使用的工具或參數。

顯然兩者都可行。你可以自己決定你喜歡哪一個。

一個主要的差異

有一些事情我相信你只能在正則表達式對象上執行。例如,如果你想匹配正則表達式的所有出現,你必須創建正則表達式對象,傳遞給它 "g" 選項,然後多次調用 re.exec() 來獲取每個匹配,直到 exec 返回 null,表示沒有更多匹配。我認為你不能用 string.match() 做到這一點。

答案#2

當使用全域標誌 g 時,match 和 exec 之間有一些差異。你不能用 match 遍歷全域出現的項目,而使用 exec 則可以:

var string="xabx xnnx";
var regexp=new RegExp('x([^x]*)x','g');

// match returns the list of matching parts:
string.match(regexp) // ["xabx", "xnnx"]

// with exec you could build a loop:
var match=regexp.exec(string);
while (match) {
    console.log(match);
    match=regexp.exec(string);
}
// This loops through matches and returns subpatterns too:
// ["xabx", "ab"]
// ["xnnx", "nn"]

當使用帶有全域化的 RegExp 對象與 match 時,index 根本不起作用:

var r=/b/g;
r.exec("0123b56b").index // 4
r.exec("0123b56b").index // 7
"0123b56b".match(r).index // undefined
"0123b56b".match(/b/).index // 4