string.match(regexp)
string:目標字符串(字面量或 String 對象)。regexp:正則表達式對象(或自動轉換為正則的字符串)。| 條件 | 返回值類型 | 數組結構 | 備註 |
|---|---|---|---|
| 無匹配 | null | — | 注意非空數組,鏈式調用需兜底 |
有匹配,無 g | Array | [fullMatch, group1, group2, ...] 含 index、input、groups 屬性 | 等同 regexp.exec(string) |
有匹配,有 g | Array | [match1, match2, ...] 純字符串數組,**無** index/input/groups,**忽略捕獲組** | 一次性獲取所有完整匹配 |
var s = "The rain in Spain falls mainly in the plain";
var r = s.match(/ain/i); // 忽略大小寫,無 g
console.log(r);
// ["ain", index: 5, input: "The rain in Spain falls mainly in the plain", groups: undefined]
// 返回首次出現 "ain" 的詳情
var r = s.match(/ain/ig); // 全局 + 忽略大小寫
console.log(r);
// ["ain", "ain", "ain", "ain"] <-- 4 次匹配,純字符串數組
var r = "The rain in Spain".match("Spain"); // 參數自動轉為 /Spain/
console.log(r); // ["Spain", index: 12, input: "The rain in Spain"]
var str = "3abc4,5abc6";
var reg = /a(bc)/g; // 有捕獲組 (bc),有 g
console.log(str.match(reg)); // ["abc", "abc"] <-- 僅完整匹配,捕獲組 "bc" 丟失!
// 若需捕獲組內容,必須用 exec 循環:
var m;
while ((m = reg.exec(str)) !== null) {
console.log(m[0], m[1]); // abc bc / abc bc
}
| 方法 | 返回 | 區分大小寫 | 支持正則 | 用途 |
|---|---|---|---|---|
match(regexp) | 匹配內容數組 / null | 受正則 i 標誌控制 | 是 | 提取匹配內容、分組 |
indexOf(str) | 首次出現索引 / -1 | 是 | 否 | 查找子串位置 |
lastIndexOf(str) | 最後出現索引 / -1 | 是 | 否 | 反向查找位置 |
var r = "abc".match(/d/); // null
// 錯誤:r.length → TypeError
// 正確:
var matches = "abc".match(/d/g) || [];
console.log(matches.length); // 0
var reg = /a/g;
"a".match(reg); // ["a"]
"b".match(reg); // null (因為 lastIndex=1,從索引1開始找)
// 解決:每次新建 /a/g 或手動 reg.lastIndex=0
// 錯誤示範:match 只能提取,不能替換
var r = "The rain in Spain".replace("Spain", "Canada"); // 正確用法
match 做不到(有 g 時丟失詳情),必須用 exec 循環:
function matchAllDetails(str, reg) {
var results = [], m;
var globalReg = new RegExp(reg.source, reg.flags + (reg.global ? '' : 'g'));
while ((m = globalReg.exec(str)) !== null) {
results.push({
match: m[0],
groups: m.slice(1),
index: m.index,
input: m.input
});
}
return results;
}
var str = "test1test2test3";
var reg = /test(\d)/g;
var iterator = str.matchAll(reg); // 返回迭代器
for (var m of iterator) {
console.log(m[0], m[1], m.index); // test1 1 0 / test2 2 5 / test3 3 10
}
// 或轉數組
var all = [...str.matchAll(reg)];
// matchAll 要求正則必須有 g 標誌,否則拋 TypeError
優勢:同時獲得「所有匹配」與「每個匹配的完整詳情(捕獲組、位置)」,完美解決 `match` 有 g 時丟失捕獲組的痛點。