JS序列化URL方法

來源:互聯網
上載者:User

標籤:

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"
  }
}

 

JS序列化URL方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.