zoukankan      html  css  js  c++  java
  • 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"
      }
    }

  • 相关阅读:
    【洛谷P3649】回文串
    【CH2401】送礼物
    Python 函数
    Python 文件操作
    JS的DOM和BOM
    JavaScript (内置对象及方法)
    JavaScript 基础(数据类型、函数、流程控制、对象)
    Python基础数据类型(数字、字符串、布尔、列表、元组、字典、集合等)
    MySQL(二)
    数据备份 及 Python 操作 Mysql
  • 原文地址:https://www.cnblogs.com/bjmumu/p/3510742.html
Copyright © 2011-2022 走看看