文章目錄
- 一、match
- 二、matchAll
一、match
match() 方法傳回一個字元串比對正規表達式的結果
str.match(reg)
reg:一個正規表達式對象,如果傳入的不是正規表達式,則會隐式的調用new RegExp(obj) 将其轉為正規表達式。如果不傳則會傳回一個包含空字元串的數組[""]
傳回值:1,如果reg使用g(全局搜尋)标志,則傳回字元串與正規表達式比對的所有結果組成的數組,如果沒有比對的字元串則傳回null
2,如果reg沒有使用g(全局搜尋)标志,則傳回第一個比對的字元串和其他相關的比對資訊。包括:
groups:一個捕獲組對象或undefined(如果沒有定義命名捕獲組)
index:比對的結果的開始索引位置
input:搜尋的字元串
const str = 'Hello JavaScript'
str.match() // [""]
str.match(/JS/) // null
str.match(/JavaScript/g) // ["JavaScript"]
str.match(/JavaScript/) // [0: "JavaScript", groups: undefined, index: 6, input: "Hello JavaScript"]
str.match(/(?<J>Java)(?<S>Script)/) // [0: "JavaScript", 1: "Java", 2: "Script", groups: { J: "Java", S: "Script" }, index: 6, input: "Hello JavaScript"]
二、matchAll
matchAll() 方法傳回一個包含所有比對正規表達式的結果及其分組捕獲組的疊代器
文法:str.matchAll(reg)
reg:正規表達式對象。如果不是正規表達式則會使用new RegExp(obj)隐式轉換為正規表達式。表達式必須設定為 g (全局模式)否則會報錯
傳回值:一個疊代器,可以使用for…of…,數組新增的擴充符(…)或Array.from()實作功能
const str = 'hello javascript hello css'
console.log(...str.matchAll(/hello/g))
// [0: "hello", groups: undefined, index: 0, input: "hello javascript hello css"]
// [0: "hello", groups: undefined, index: 17, input: "hello javascript hello css"]
// 0: "hello" 比對的字元串,如果有使用分組會在後面依次列出來
// groups: undefined 沒有使用命名捕獲組會傳回undefined,否則會傳回包含命名捕獲組的對象
// index: 0 比對的結果在目前字元串位置開始的索引
// input: "hello javascript hello css" 目前字元串