js解析url

输入:http://www.js-51.com/news/2012-5/GUANLIRUANJIANYAOBUYAOBAYIYONGXINGFANGZAIZHONGYAOWEIZHI.html?q=all&l=zh-cn#go
1 href
全部URl字符串(在浏览器中就是完整的地址栏)
返回: http://www.js-51.com/news/2012-5/GUANLIRUANJIANYAOBUYAOBAYIYONGXINGFANGZAIZHONGYAOWEIZHI.html?q=all&l=zh-cn#go

2 protocol
URL 的协议部分
返回:http:

3 host
URL 的主机部分
返回:www.js-51.com

4 port
URL 的端口部分
假如采用默认的80端口(即使添加了:80),那么返回值并不是默认的80而是空字符
返回:""

5 pathname
URL 的路径部分(就是文件地址)
返回:/news/2012-5/GUANLIRUANJIANYAOBUYAOBAYIYONGXINGFANGZAIZHONGYAOWEIZHI.html?q=all&l=zh-cn#go

6 search
查询(参数)部分
返回:?q=all&l=zh-cn

7 hash
锚点
返回:#go

 

 1 var r = {
 2     protocol: /([^\/]+:)\/\/(.*)/i,
 3     host: /(^[^\:\/]+)((?:\/|:|$)?.*)/,
 4     port: /\:?([^\/]*)(\/?.*)/,
 5     pathname: /([^\?#]+)(\??[^#]*)(#?.*)/
 6 };
 7 
 8 function parseUrl(url) {
 9     var tmp, res = {};
10     res["href"] = url;
11     for (p in r) {
12         tmp = r[p].exec(url);
13         res[p] = tmp[1];
14         url = tmp[2];
15         if (url === "") {
16             url = "/";
17         }
18         if (p === "pathname") {
19             res["pathname"] = tmp[1];
20             res["search"] = tmp[2];
21             res["hash"] = tmp[3];
22         }
23     }
24     console.log(url);
25     return res;
26 };
console.log(
    parseUrl("http://www.j-5.com:10000"),
    parseUrl("http://j-5.com/#go"),
    parseUrl("https://www.j-5.com/abc/def.htm#go"),
    parseUrl("https://j-5.net/abc/def.htm?q=all&l=zh-cn"),
    parseUrl("https://j-5.cn:10000/news/def.htm?q=all&l=en-us#go"),
    parseUrl("http://www.js-dom.com:10000/about/company.htm"),
    parseUrl("http://www.js-dom.com/news/2012-5/RIJUAN.html?q=all&l=zh-cn#go")
);

  貌似输出正常了,url解析成功。

posted @ 2012-05-16 23:19  陈锐达  阅读(6396)  评论(0编辑  收藏  举报