一个不错的JavaScript解析浏览器路径方法(转)

本文介绍了一种使用JavaScript解析URL各个组成部分的方法,通过创建HTML链接元素并利用其属性来提取URL的协议、主机名、端口、查询参数等。

JavaScript中有时需要用到当前的请求路径等涉及到url的情况,正常情况下我们可以使用location对象来获取我们需要的信息,本文从另外一个途径来解决这个问题,而且更加巧妙

方法如下:

 1 function parseURL(url) {
 2 var a =  document.createElement('a');
 3 //创建一个链接
 4 a.href = url;
 5 return {
 6 source: url,
 7 protocol: a.protocol.replace(':',''),
 8 host: a.hostname,
 9 port: a.port,
10 query: a.search,
11 params: (function(){
12 var ret = {},
13 seg = a.search.replace(/^\?/,'').split('&'),
14 len = seg.length, i = 0, s;
15 for (;i<len;i++) {
16 if (!seg[i]) { continue; }
17 s = seg[i].split('=');
18 ret[s[0]] = s[1];
19 }
20 return ret;
21 })(),
22 file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
23 hash: a.hash.replace('#',''),
24 path: a.pathname.replace(/^([^\/])/,'/$1'),
25 relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
26 segments: a.pathname.replace(/^\//,'').split('/')
27 };
28 }

使用方法如下:

 1 var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
 2 myURL.file;     // = 'index.html'
 3 myURL.hash;     // = 'top'
 4 myURL.host;     // = 'abc.com'
 5 myURL.query;    // = '?id=255&m=hello'
 6 myURL.params;   // = Object = { id: 255, m: hello }
 7 myURL.path;     // = '/dir/index.html'
 8 myURL.segments; // = Array = ['dir', 'index.html']
 9 myURL.port;     // = '8080'
10 myURL.protocol; // = 'http'
11 myURL.source;   // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

 

转载于:https://www.cnblogs.com/ljack/p/3577439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值