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解析成功。

转载于:https://www.cnblogs.com/chanruida/archive/2012/05/16/2505544.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值