Home  >  Q&A  >  body text

javascript - 将url后的参数键值对转换成JSON数组格式效率最高的方法?


http: //www.a.com/admin/index.php#route=main/nav&user=tom&id=123/profile

后的参数转换成:

    [
    {"router":"main"},
    {
    "nav":"",
    "user":"tom",
    "id":"123"
    },
    {"profile":""}
    ]

除了循环变量有没有更简洁的方法

巴扎黑巴扎黑2645 days ago694

reply all(5)I'll reply

  • 迷茫

    迷茫2017-04-11 10:14:38

    坐等更好方案:

    'use strict';
    
    var url = 'http: //www.a.com/index.php?route=main&nav&user=tom&id=123&profile';
    
    var querys = url
        .substring(url.indexOf('?') + 1)
        .split('&')
        .map((query) => query.split('='))
        .reduce((params, pairs) => (params[pairs[0]] = pairs[1] || '', params), {});
    
    console.log(querys);
    //{ route: 'main', nav: '', user: 'tom', id: '123', profile: '' }

    Reply
    0
  • PHPz

    PHPz2017-04-11 10:14:38

    var url = location.search.substr(1);
        param = {};
    console.log(url);
    url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
        param[v] = decodeURIComponent(k);
        return k + '=' +  v;
    });
    console.log(param);

    Reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-11 10:14:38

    http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

    Reply
    0
  • 巴扎黑

    巴扎黑2017-04-11 10:14:38

    var url = 'http: //www.a.com/admin/index.php?route=main/nav=&user=tom&id=123/profile',
        result = [];
    
    url.substring(url.indexOf('?') + 1)
        .replace(/[^\/]+/g, function(objstr) {
            var obj = {},
                empty = false;
            objstr.replace(/([^\/&=]+)(=([^\/&=]+)?)?/g, function(s, a, b, c) {
                if(a && b && c){
                    obj[a] = c;
                }else if(a && !c){
                    obj[a] = '';
                }else{
                    empty = true;
                }
            });
            if(!empty){
                result.push(obj);
            }
        });
    
    console.log(result);

    Reply
    0
  • PHP中文网

    PHP中文网2017-04-11 10:14:38

    我觉得用正则表达式将简单的问题搞复杂了。本来就一个很简单的字符串分解的工作,却要弄出一个很复杂的正则表达式,正则表达式看起来很反人类的说。1楼的同学用了太多jquery的函数。也不是我喜欢的。简单的工作就简单的解决即可。速度快无依赖。
    可以试试下面的代码:

    <script>
    var url = 'http: //www.a.com/index.php?route=main&nav&user=tom&id=123&profile';
    
    var querys = url
        .substring(url.indexOf('?') + 1)
        .split('&');
    var result={};
    for(var i=0;i<querys.length;i++){
        var temp=querys[i].split('=');
        if(temp.length<2){
            result[temp[0]]='';
        }else{
            result[temp[0]]=temp[1];
        }
    }
    console.log(result);
    </script>

    Reply
    0
  • CancelReply