DIV CSS 佈局教程網

實測 JavaScript 中 match() 與 exec() 的返回值與屬性
編輯:關於JavaScript     

語法:

 exec() : RegExpObject.exec(string) match() : stringObject.match(string) stringObject.match(regexp) 

知識點:

exec() 是 RegExp 對象的方法,而 match() 是 String 對象的方法。二者都會返回一個包含首個匹配項信息的數組;若沒有匹配項,則返回 null。

返回的數組雖然是 Array 的實例,卻額外掛著兩個屬性:index 與 input。其中,index 表示匹配項在字符串中的位置,input 則表示被應用正則表達式的原始字符串。數組的第一項是與整個模式匹配的字符串,其餘各項依次對應模式中的各個捕獲組(若模式中沒有捕獲組,數組便只含一項)。

實測:

對 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() 的測試結果截圖:

RegExp 對象方法

方法 描述
exec 檢索字符串中指定的值,返回找到的結果並確定其位置
test 檢索字符串中指定的值,返回 true 或 false

String 對象方法

方法 描述
match() 找到一個或多個正則表達式的匹配
replace() 替換與正則表達式匹配的子串
search() 檢索與正則表達式相匹配的值

以上就是關於 JavaScript 中 match() 與 exec() 返回值及屬性的實測介紹,希望對你有所幫助!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved