The inverse function of $.param() in jQuery

jQuery has a useful function to serialize an object into url query string, which called $.param().

For example:

$.param({ a: 2, b: 3, c: 4 }) 	// "a=2&b=3&c=4"
$.param({ a: [2, 3, 4] }) 	// "a=2&a=3&a=4"

Sometimes we want do the opposite thing: we want to convert the url query string into an object. This process can be called deserialize the url query string. Unfortunately, I didn'’t find any method in jQuery to achive this, so I had to write my own one.

I named this function as “deserializeUrlParams()” and encapsulated it into zizhujy.com namespace. The code lists as below:

var zizhujy = {};
zizhujy.com = {
    //
    // let object refer to value
    // Usage: object = zizhujy.com.set(object, value);
    //
    set: function (object, value) {
        if (object == null) {
            object = value;
        } else {
            if (object instanceof Array) {
                object.push(value);
            } else {
                var o = object;
                object = [];
                object.push(o);
                object.push(value);
            }
        }

        return object;
    },

    //
    // Usage: zizhujy.com.deserializeUrlParams("a=2&b=3") --> {a:2, b:3}
    //          zizhujy.com.deserializeUrlParams("a=2&a=3&a=4") --> {a: [2, 3, 4]}
    //          zizhujy.com.deserializeUrlParams() <==> deserializeUrlParams(window.location.search.substring(1))
    //
    deserializeUrlParams: function () {
        var urlParams = null;
        var expression;
        // Regex for replacing addition symbol with a space
        var a = /\+/g;
        var reg = /([^&=]+)=?([^&]*)/g;
        var d = function (s) { return decodeURIComponent(s.replace(a, " ")); };

        var q = "";
        if (arguments.length > 0) q = arguments[0];
        else q = window.location.search.substring(1);

        while (expression = reg.exec(q)) {
            if (urlParams == null) urlParams = {};
            urlParams[d(expression[1])] = this.set(urlParams[d(expression[1])], d(expression[2]));
        }

        return urlParams;
    }
};

You can test it out by here.

deserialize the url query string

Add comment

Loading