js深度解析url地址

“站在巨人的肩膀上”html

灵感来源:web

https://segmentfault.com/a/1190000004601319

segmentfault

http://mp.weixin.qq.com/mp/ad_biz_info?__biz=MzAwMjU3OTY5NQ==#wechat_webview_type=2&wechat_redirect

上面一个地址,可让你学到如何解析一个url地址,从中解析出每个参数内容
第二个连接的问题就是参数中的键值对出现了==号,这是base64信息,若是再用=切割,就会出问题,这里就改版了一下浏览器

String.prototype.parseURL = function(){
    var url =this.toString()
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        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('/'),
        params: (function() {
            var ret = {};
            var seg = a.search.replace(/^\?/, '').split('&').filter(function(v,i){
                if (v!==''&&v.indexOf('=')) {
                    return true;
                }
            });
            seg.forEach( function(element, index) {
                var idx = element.indexOf('=');
                var key = element.substring(0, idx);
                var val = element.substring(idx+1);
                ret[key] = val;
            });
            return ret;
        })()
    };
}

调用方法:测试

location.href.parseURL();

'http://a.com:8888/a/b.html?c=1&0=0&d===&=1'.parseURL();
//上面故意把参数写的很乱,为了测试,若是上面你的浏览器报错,说明版本较低,能够以下写法

('http://a.com:8888/a/b.html?c=1&0=0&d===&=1').parseURL();
相关文章
相关标签/搜索