match() 方法依正則表達式檢索字串,行為隨 g (global) 旗標而異。是字串解析、資料擷取、格式驗證的核心工具。
str.match(regexp)
| 模式 | 旗標 | 回傳值 |
|---|---|---|
| 非全域 | 無 g | 同 RegExp.exec():[match, group1, ..., index, input, groups] 或 null |
| 全域 | 有 g | 所有匹配字串組成的陣列 [match1, match2, ...],無匹配回傳 null |
<script>
const str = 'Chapter 3.4.5.1';
const re = /(chapter\s+\d+(\.\d+)*)/i;
const result = str.match(re);
console.log(result[0]); // 'Chapter 3.4.5.1' (完整匹配)
console.log(result[1]); // 'Chapter 3.4.5.1' (第1群組)
console.log(result[2]); // '.1' (第2群組)
console.log(result.index); // 0
console.log(result.input); // 原字串
</script>
<script>
const str = 'A1 B2 C3 D4';
const re = /\d/g;
console.log(str.match(re)); // ['1', '2', '3', '4']
// 注意:全域模式下不提供群組資訊與索引
// 需群組資訊請使用 matchAll() (ES2020)
for (const match of str.matchAll(/([A-Z])(\d)/g)) {
console.log(match[0], match[1], match[2]); // A1 A 1, B2 B 2...
}
</script>
str.match('abc') 等同 str.match(/abc/)。lastIndex 會保留狀態,重複呼叫需手動歸零或改用 matchAll()。const matches = [...str.matchAll(/(\w+)@(\w+)\.(\w+)/g)];
// 每個 match 為完整結果陣列,含群組、索引、groups
理解 match() 兩種模式差異至關重要。需群組資訊且全域搜尋時,請改用 matchAll() 獲得完整、可迭代的結果。