JS序列化URL方法

function serializeUrl(str){
    var param = {}, hash = {}, anchor;
    var url = str || location.href;
    var arr = /([^?]*)([^#]*)(.*)/.exec(url);
    var ar1 = /^(http|ftp)/.test(arr[1]) ? /(.*?:)?(?:\/?\/?)([\.\w]*)(:\d*)?(.*?)([^\/]*)$/.exec(arr[1]) : /(.*?)([^\/]*)$/.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];
    }
  !/^(http|ftp)/.test(arr[1]) && ar1.splice(1, 0, undefined, undefined, undefined);
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:",
  "host": "www.baidu.com",
  "port": ":80",
  "path": "/fuwu_bone/html/",
  "file": "orderlist.html",
  "param": {
    "a": "1",
    "b": "2"
  },
  "hash": {
    "c": "3"
  }
}

 

posted @ 2015-02-05 11:46  北京-木木  阅读(2670)  评论(0编辑  收藏  举报