Justin's Words

JavaScript 判断 URL

1
2
3
var URL_REGEXP = /^(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?$/;
var url = "https://g.taobao.com/brand_detail.htm?navigator=all&_input_charset=utf-8&q=%E7%94%B7%E5%A3%AB%E8%A1%AC%E8%A1%AB%E8%8B%B1%E4%BC%A6%E6%AC%BE&spm=5148.1292865.a31d2.2.NiXIQv";
URL_REGEXP.test(url); // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 来自 stackoverflow
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}

参考