文法:
exec() :RegExpObject.exec(string) match() :stringObject.match(string)stringObject.match(regexp)
知識點:
exec() 是RegExp對象的方法,而 match() 是String對象的方法。
都會返回包含第一個匹配項資訊的數組;或者在沒有匹配項的情況下返回null。
返回的數組雖然是Array 的執行個體,但包含兩個額外的屬性:index 和 input。其中,index 表示匹配項在字串中的位置,而 input 表示應用Regex的字串。
在數組中,第一項是與整個模式比對的字串,其他項是與模式中的擷取的群組匹配的字串(如果模式中沒有擷取的群組,則該數組只包含一項)。
測試:
對 match() 的測試代碼:
var text = "mom and dad and baby";var pattern = /(mom and )?(dad and )?baby/;var matches = text.match(pattern);//pattern.exec(text);console.log(matches.index);console.log(matches.input);console.log(matches[0]);console.log(matches[1]);console.log(matches[2]);
對 match() 的測試結果截圖:
對 exec() 的測試代碼:
var text = "mom and dad and baby";var pattern = /(mom and )?(dad and )?baby/;var matches = pattern.exec(text);//text.match(pattern);console.log(matches.index);console.log(matches.input);console.log(matches[0]);console.log(matches[1]);console.log(matches[2]);
對 exec() 的測試結果截圖:
String 對象方法
| 方法 |
描述 |
| exec |
檢索字串中指定的值。返回找到的值,並確定其位置 |
| test |
檢索字串中指定的值。返回 true 或 false。 |
String 對象方法
| 方法 |
描述 |
| match() |
找到一個或多個Regex的匹配。 |
| replace() |
替換與Regex匹配的子串。 |
| search() |
檢索與Regex相匹配的值。 |
關於JS中match() 和 exec() 傳回值和屬性的測試就給大家介紹到這裡,希望對大家有所協助!