match() 會使用正則表達式搜尋字串,並傳回比對結果。若正則表達式沒有 g 標記,結果類似 exec();若有 g 標記,則會傳回所有符合項目組成的陣列。
string.match(regexp)
參數必須是 RegExp 物件。若沒有符合結果,會傳回 null。
const str = 'For more information, see Chapter 3.4.5.1';
const re = /(chapter \d+(\.\d)*)/i;
const found = str.match(re);
console.log(found);
此範例會找出 Chapter 3.4.5.1 的內容。若需要取得所有符合項,可在正則表達式中加上 g 標記。