正則表達式匹配URL


正則表達式:

復制代碼
var match = /^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/;
/* 
注:
(1)、如需允許其他聯接方式,可以修改“(ht|f)tps?”部分,在“?”后面跟上符號“|”,然后加上您需要的聯接方式,多個時用符號“|”分隔)。
(2)、如需允許URL參數包含其它字符,可以修改“[\w\-\.,@?^=%&:\/~\+#]”,以設置您需要的參數。
*/
復制代碼

匹配:

(1)、直接匹配域名地址:

復制代碼
var matchString = 'https://i.cnblogs.com';
console.log(match.test(matchString)); // ==> true
var matchString = 'https://i.cnblogs.com/';
console.log(match.test(matchString)); // ==> true
var matchString = 'https://i.cnblogs.com//'; // ==> 不允許非域名或參數以外的地方出現雙“/”;
console.log(match.test(matchString)); // ==> false
復制代碼

(2)、匹配鏈接含(*.htm,*.html,*.php,*.aspx...)后綴的地址:

復制代碼
var matchString = 'https://i.cnblogs.com/EditPosts.aspx';
console.log(match.test(matchString)); // ==> true
var matchString = 'https://i.cnblogs.com./EditPosts.aspx'; // ==> 不允許參數以外的地方以雙“.”結尾;
console.log(match.test(matchString)); // ==> false
復制代碼

(3)、匹配含參數的地址:

復制代碼
var matchString = 'https://i.cnblogs.com/EditPosts.aspx?opt=1';
console.log(match.test(matchString)); // ==> true
var matchString = 'https://i.cnblogs.com/EditPosts.aspx?opt=1&user='
console.log(match.test(matchString)); // ==> true
復制代碼

使用說明:

(1)、地址必須以http/https/ftp/ftps開頭;

(2)、地址不能包含雙字節符號或非鏈接特殊字符。

 

完美,只是因為簡單。
 
分類:  js, reg
轉載:http://www.cnblogs.com/jschar/p/6092585.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM