與正則有關的JS方法結合其在項目中的應用
與正則有關的JS方法結合其在項目中的應用
前言
最近項目中用到正則匹配比較多,因此打算深入理解和總結下各個與正則有關的方法,再結合在項目中使用的情況。與正則有關的JS方法共有7個,分別是RegExp對象的compile(), exec(), test() 和支持正則表達式的的String()方法為search(), match(), replace(), split()。
RegExp對象方法
compile()方法
該方法用於改變和重新編譯正則表達式。語法: RegExpObject.compile(regexp, modifier); 參數1是正則表達式,參數2是規定匹配的類型。“g”用於全局匹配,“i”用於區分大小寫,“gi”用於全局區分大小寫的匹配。
1 var str = ‘hello world hello world‘; 2 var patt = /hello/g; 3 //在全局使用"hi"字符串替換"hello" 4 var str2 = str.replace(patt, ‘hi‘); 5 console.log(str2); 6 patt = /world/g; 7 patt.compile(patt); 8 //在全局使用"all the world"字符串替換"world" 9 str2 = str.replace(patt, ‘all the world‘); 10 console.log(str2);
在控制臺輸入如有圖 :
exec()方法
該方法用於檢索字符串中的正則表達式的匹配。 語法:RegExpObject.exec(string). 參數為要檢索的字符串。返回值:返回一個數組,其中存放匹配的結果,若未找到匹配,則返回null。
1 var str= "Visit W3School, W3School is a place to study web technology."; 2 var patt1 = new RegExp("W3School","g"); 3 var patt2 = new RegExp("W3School"); 4 var result; 5 while((result = patt1.exec(str)) != null) { 6 console.log(result); 7 console.log(patt1.lastIndex); 8 } 9 //跳出循環後,返回null,並將lastIndex值重置為0 10 console.log(patt1.lastIndex); 11 12 console.log(patt2.exec(str)); 13 console.log(patt2.lastIndex); 14 /* 15 while ((result = patt2.exec(str)) != null) { 16 console.log(result); 17 console.log(patt2.lastIndex); 18 } 19 註意: 此循環是一個死循環,非全局匹配只匹配第一次匹配到的值patt2.exec(str))返回一個數組。 20 */
圖(1) 圖(2)
除了數組元素和 length 屬性之外,exec() 方法還返回兩個屬性。index 屬性聲明的是匹配文本的第一個字符的位置。input 屬性則存放的是被檢索的字符串 string。我們可以看得出,在調用非全局的 RegExp 對象的 exec() 方法時(如變量patt2,圖(2)),返回的數組與調用方法 String.match() 返回的數組是相同的,lastIndex 默認是0。
但是,當 RegExpObject 是一個全局正則表達式時(如變量patt1,圖(1)),exec() 的行為就稍微復雜一些。它會在 RegExpObject 的 lastIndex 屬性指定的字符處開始檢索字符串 string。當 exec() 找到了與表達式相匹配的文本時,在匹配後,它將把 RegExpObject 的 lastIndex 屬性設置為匹配文本的最後一個字符的下一個位置。這就是說,您可以通過反復調用 exec() 方法來遍歷字符串中的所有匹配文本。當 exec() 再也找不到匹配的文本時,它將返回 null,並把 lastIndex 屬性重置為 0。通過圖(1),我們看到第一次檢索到‘W3Cschool‘時,Index值為6,而lastIndex變為14,然後從lastIndex 處開始檢索字符串,第二次檢索到‘W3Cschool‘,而lastIndex變為24。最後退出循環,lastIndex重置為0。
test()方法
該方法用於檢測一個字符串是否匹配某個模式。語法:RegExpObject.test(string);返回值:如果字符串string中含有與RegExpObject匹配的文本,則返回true,否則false。下面貼下在項目中使用到的正則應用,手機號碼驗證:
1 var reg = /(13\d|14[57]|15[^4,\D]|17[678]|18\d)\d{8}|170[059]\d{7}/; 2 //登錄事件 3 $(".lonBtn").click(function() { 4 var num = $("#phoneNum").val(); 5 var code = $("#code").val(); 6 if( !reg.test(num) || code == ‘‘ ) { 7 mui.alert("手機號碼或者驗證碼錯誤"); 8 } else { 9 window.location.href = "memAbout.html"; 10 } 11 })
匹配圖片格式正則:
//上傳圖片函數 function uploadImg(domEle) { $(domEle).change(function() { if ( typeof FileReader === ‘undefined‘ ) { alert("你的瀏覽器不支持FileReader"); return; } var file = this.files[0]; console.log(file); //圖片格式正則 if ( !/(.*).(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/.test(file.name) ) { alert("請上傳圖片格式內容"); return; } // if ( file.size / 1024 > 5 ) { //file.size圖片大小單位是B,轉換為KB。 // alert("上傳圖片大小不應超過5KB"); // return; // } var r = new FileReader(); r.readAsDataURL(file); r.onload = function(e) { // console.log(this.result); $(domEle).next().html(‘<img src="‘ + this.result + ‘" alt="圖片">‘); } }) }
String對象方法
search()方法
該方法用於檢索字符串中指定的子字符串或檢索與正則表達式相匹配的子字符串。語法:stringObejct.search(regexp),返回值:第一個與regexp相匹配的子串的起始位置。沒有找到返回-1.特別註意search()方法不執行全局匹配。
var str4 = "hello3 w4orld"; //檢索指定的子字符串 console.log(str4.search(/wor/)); // -1 //檢索與正則表達式匹配的子字符串 非全局 console.log(str4.search(/\d/)); // 5 // 全局匹配 console.log(str4.search(/\d/g)); // 5
由在全局匹配和非全局匹配返回值都一樣,說明確實不執行全局匹配。
match()方法
該方法可在字符串內檢索指定的值,或找到一個或多個正則表達式的匹配。語法:stringObject.match(searchvalue)或stringObject(regexp)。返回值: 存放匹配結果的數組。該數組的內容依賴於regexp是否具有全局標識g。
var str= "Visit W3School, W3School is a place to study web technology."; console.log(str.match(‘W3School‘)); // 參數為RegExp對象 全局搜索 console.log(str.match(/\d+/g)); // 參數為RegExp對象 非全局搜索 只執行一次匹配 console.log(str.match(/\d+/));
圖(3)
在調用String 對象的 metch() 方法時,參數為非全局搜索,返回的數組與調用方法RegExp.exec() 返回的數組是相同的。不過全局匹配返回的數組的內容與前者大不相同,它的數組元素中存放的是 stringObject 中所有的匹配子串,而且也沒有 index 屬性或 input 屬性。如圖(3)
獲取請求參數地址:
/** * 獲取請求地址參數 * @param String name */ function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象 // 正則是尋找&+url參數名字=值+& console.log(reg); // /(^|&)index=([^&]*)(&|$)/ var search = encodeURI(window.location.search); console.log(search); // ?index=1 var r = search.substr(1).match(reg); //匹配目標參數 console.log(r); //["index=1", "", "1", "", index: 0, input: "index=1"] if (r != null) return decodeURI(unescape(r[2])); return null; //返回參數值 }; var Gindex = getUrlParam("index");
replace()方法
該方法用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。語法: stringObject.repalce(regexp/substr, replacement); 返回值:一個新的字符串。註意:如果regexp具有全局標識g,那麽replace()方法將替換所有匹配的子串。否則它只替換第一個匹配的子串。
split()方法
該方法用於把一個字符串分割成字符串數組。語法: stringObject.split(separator, howmany); 第一個參數:字符串或正則表達式。第二個參數:可選,該參數可指定返回的數組的最大長度。
1 var str5 = "15hell1o w3o"; 2 console.log(str5.split(/\d+/)); // ["", "hell", "o w", "o"] 3 // 空字符串("")作為分割,那麽字符串每個字符之間都會被分割。 4 console.log(str5.split("")); //
與正則有關的JS方法結合其在項目中的應用