How to convert URL parameters to a JavaScript object?

前端 未结 30 1365
时光取名叫无心
时光取名叫无心 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:43

    This seems to be the best solution as it takes multiple parameters of the same name into consideration.

        function paramsToJSON(str) {
            var pairs = str.split('&');
            var result = {};
            pairs.forEach(function(pair) {
                pair = pair.split('=');
                var name = pair[0]
                var value = pair[1]
                if( name.length )
                    if (result[name] !== undefined) {
                        if (!result[name].push) {
                            result[name] = [result[name]];
                        }
                        result[name].push(value || '');
                    } else {
                        result[name] = value || '';
                    }
            });
            return( result );
        }
    
    something
    paramsToJSON("x=1&x=2&x=3&y=blah"); 
    
    console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON
    

    I later decided to convert it to a jQuery plugin too...

    $.fn.serializeURLParams = function() {
        var result = {};
    
        if( !this.is("a") || this.attr("href").indexOf("?") == -1 ) 
            return( result );
    
        var pairs = this.attr("href").split("?")[1].split('&');
        pairs.forEach(function(pair) {
            pair = pair.split('=');
            var name = decodeURI(pair[0])
            var value = decodeURI(pair[1])
            if( name.length )
                if (result[name] !== undefined) {
                    if (!result[name].push) {
                        result[name] = [result[name]];
                    }
                    result[name].push(value || '');
                } else {
                    result[name] = value || '';
                }
        });
        return( result )
    }
    
    something
    $("a").serializeURLParams(); 
    
    console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON
    

    Now, the first will accept the parameters only but the jQuery plugin will take the whole url and return the serialized parameters.

提交回复
热议问题