How to convert URL parameters to a JavaScript object?

前端 未结 30 1061
时光取名叫无心
时光取名叫无心 2020-11-22 13:57

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
          


        
30条回答
  •  心在旅途
    2020-11-22 14:46

    I had the same problem, tried the solutions here, but none of them really worked, since I had arrays in the URL parameters, like this:

    ?param[]=5¶m[]=8&othr_param=abc¶m[]=string
    

    So I ended up writing my own JS function, which makes an array out of the param in URI:

    /**
     * Creates an object from URL encoded data
     */
    var createObjFromURI = function() {
        var uri = decodeURI(location.search.substr(1));
        var chunks = uri.split('&');
        var params = Object();
    
        for (var i=0; i < chunks.length ; i++) {
            var chunk = chunks[i].split('=');
            if(chunk[0].search("\\[\\]") !== -1) {
                if( typeof params[chunk[0]] === 'undefined' ) {
                    params[chunk[0]] = [chunk[1]];
    
                } else {
                    params[chunk[0]].push(chunk[1]);
                }
    
    
            } else {
                params[chunk[0]] = chunk[1];
            }
        }
    
        return params;
    }
    

提交回复
热议问题