JS序列化URL方法

function serializeUrl(str){
    var param = {}, hash = {}, anchor;
    var url = str || location.href;
    var arr = /([^?]*)([^#]*)(.*)/.exec(url);
    var ar1 = /(.*:)?(?:\/?\/?)([\.\w]*)(:\d*)?(.*?)([^\/]*)$/.exec(arr[1]);
    var ar2 = arr[2].match(/[^?&=]*=[^?&=]*/g);
    var ar3 = arr[3].match(/[^#&=]*=[^#&=]*/g);

    if(ar2){
        for(var i = 0, l = ar2.length; i < l; i++){
            var ar22 = /([^=]*)(?:=*)(.*)/.exec(ar2[i]);
            param[ar22[1]] = ar22[2];
        }
    }
    
    if(ar3){
        for(var i = 0, l = ar3.length; i < l; i++){
            var ar33 = /([^=]*)(?:=*)(.*)/.exec(ar3[i]);
            hash[ar33[1]] = ar33[2];
        }
    }

    if(arr[3] && !/[=&]/g.test(arr[3])){
        anchor = arr[3];
    }

    function getUrl(){
        var that = this, url = [], param = [], hash = [];

        url.push(that.protocol, that.protocol && ‘//‘ || ‘‘, that.host, that.port, that.path, that.file);

        for(var p in that.param){
            param.push(p+ ‘=‘ +that.param[p]);
        }

        for(var p in that.hash){
            hash.push(p+ ‘=‘ +that.hash[p]);
        }

        url.push(param.length && ‘?‘ + param.join(‘&‘) || ‘‘);

        if(that.anchor){
            url.push(that.anchor);
        }else{
            url.push(hash.length && ‘#‘ + hash.join(‘&‘) || ‘‘);
        }

        return url.join(‘‘);
    }

    return {
        href: arr[0],
        protocol: ar1[1],
        host: ar1[2],
        port: (ar1[3] || ‘‘),
        path: ar1[4],
        file: ar1[5],
        param: param,
        hash: hash,
        anchor: anchor,
        getUrl: getUrl
    };
};


 

举例:
serializeUrl(‘http://www.baidu.com:80/fuwu_bone/html/orderlist.html?a=1&b=2#c=3‘)

返回结果:

{
  "href": "http://www.baidu.com:80/fuwu_bone/html/orderlist.html?a=1&b=2#c=3",
  "protocol": "http://www.baidu.com:",
  "host": "80",
  "port": "",
  "path": "/fuwu_bone/html/",
  "file": "orderlist.html",
  "param": {
    "a": "1",
    "b": "2"
  },
  "hash": {
    "c": "3"
  }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。