關(guān)于JS中match() 和 exec() 返回值和屬性的測試
語法:
exec() : RegExpObject.exec(string) match() : stringObject.match(string) stringObject.match(regexp)
知識點:
exec() 是RegExp對象的方法,而 match() 是String對象的方法。
都會返回包含第一個匹配項信息的數(shù)組;或者在沒有匹配項的情況下返回null。
返回的數(shù)組雖然是Array 的實例,但包含兩個額外的屬性:index 和 input。其中,index 表示匹配項在字符串中的位置,而 input 表示應(yīng)用正則表達式的字符串。
在數(shù)組中,第一項是與整個模式匹配的字符串,其他項是與模式中的捕獲組匹配的字符串(如果模式中沒有捕獲組,則該數(shù)組只包含一項)。
測試:
對 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() 的測試結(jié)果截圖:
對 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() 的測試結(jié)果截圖:
String 對象方法
方法 | 描述 |
exec | 檢索字符串中指定的值。返回找到的值,并確定其位置 |
test | 檢索字符串中指定的值。返回 true 或 false。 |
String 對象方法
方法
描述
match()
找到一個或多個正則表達式的匹配。
replace()
替換與正則表達式匹配的子串。
search()
檢索與正則表達式相匹配的值。
關(guān)于JS中match() 和 exec() 返回值和屬性的測試就給大家介紹到這里,希望對大家有所幫助!
相關(guān)文章
JavaScript?onclick點擊事件-點擊切換圖片且自動播放
這篇文章主要介紹了JavaScript?onclick點擊事件-點擊切換圖片且自動播放,在頁面中放圖片并設(shè)置四個button,可以通過點擊上一張下一張來切換圖片,下面來看看具體的實現(xiàn)過程吧2022-01-01javascript 函數(shù)及作用域總結(jié)介紹
本文是對javascript在的函數(shù)及作用域進行了詳細的總結(jié)介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11