js-url解析函数

//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 url ="http://www.baidu.com?name=aaa";
console.log(parseURL(url).protocol)//http
console.log(parseURL(url).params.name)//aaa

  

 

posted @ 2016-10-18 16:19  小虫1  阅读(1414)  评论(0编辑  收藏  举报