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‘