url解析

function parseURL(url) {
 var a =  document.createElement('a');  
 a.href = url;  
 return {  
 source: url,  
 protocol: a.protocol.replace(':',''),  
 host: a.hostname,  
 port: a.port,  
 query: a.search,  
 params: (function(){  
     var ret = {},  
         seg = a.search.replace(/^\?/,'').split('&'),  
         len = seg.length, i = 0, s;  
     for (;i<len;i++) {  
         if (!seg[i]) { continue; }  
         s = seg[i].split('=');  
         ret[s[0]] = s[1];  
     }  
     return ret;  
 })(),  
 file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],  
 hash: a.hash.replace('#',''),  
 path: a.pathname.replace(/^([^\/])/,'/$1'),  
 relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],  
 segments: a.pathname.replace(/^\//,'').split('/')  
 };  
}    
 
var myURL = parseURL('http://192.168.10.17:10008/info/qwewq?tag_id=21&page=3#link');
console.log(myURL.path);//获取URL 的路径部分(就是文件地址) 返回:/info/qwewq
console.log(myURL.segments);//获取URL 的路径部分(就是文件地址)并存储为数组 返回:["info", "qwewq"]
console.log(myURL.file);//获取url 文件 返回:qwewq
console.log(myURL.query);// 获取url ?到#号之间的参数 返回:?tag_id=21&page=3
console.log(myURL.params);//获取url ?到#号之间的参数并存储为对象 返回:Object {tag_id: "21", page: "3"}
console.log(myURL.hash);//获取URL#后边的参数 返回:link
console.log(myURL.host);//获取url 主机名 返回:192.168.10.17
console.log(myURL.protocol);//获取url 协议头 返回:http
console.log(myURL.source);//获取url 完整地址 返回:http://192.168.10.17:10008/info/qwewq?tag_id=21&page=3#link
console.log(myURL.port);//获取url 端口号 返回:10008


1, window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)

2,window.location.protocol
URL 的协议部分
本例返回值:http:

3,window.location.host
URL 的主机部分
本例返回值:192.168.10.17

4,window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:10008

5,window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/info/qwewq

6,window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?tag_id=21&page=3

7,window.location.hash
锚点
本例返回值:#link

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值