Skip to content

Instantly share code, notes, and snippets.

@kares
Created May 5, 2011 11:28
Show Gist options
  • Save kares/956897 to your computer and use it in GitHub Desktop.
Save kares/956897 to your computer and use it in GitHub Desktop.
jQuery.parseParams - parse query string paramaters into an object
/**
* $.parseParams - parse query string paramaters into an object.
*/
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
@Komrod
Copy link

Komrod commented Mar 14, 2014

And also, a function that converts object to URL is handy :-)
Fiddle: http://jsfiddle.net/cADUU/4/

// Encode an object to an url string
// This function return the search part, begining with "?"
// Use: $.encodeURL({var: "test", len: 1}) returns ?var=test&len=1
(function ($) {
    $.encodeURL = function (object) {

        // recursive function to construct the result string
        function createString(element, nest) {
            if (element === null) return '';
            if ($.isArray(element)) {
                var count = 0,
                    url = '';
                for (var t = 0; t < element.length; t++) {
                    if (count > 0) url += '&';
                    url += nest + '[]=' + element[t];
                    count++;
                }
                return url;
            } else if (typeof element === 'object') {
                var count = 0,
                    url = '';
                for (var name in element) {
                    if (element.hasOwnProperty(name)) {
                        if (count > 0) url += '&';
                        url += createString(element[name], nest + '.' + name);
                        count++;
                    }
                }
                return url;
            } else {
                return nest + '=' + element;
            }
        }

        var url = '?',
            count = 0;

        // execute a createString on every property of object
        for (var name in object) {
            if (object.hasOwnProperty(name)) {
                if (count > 0) url += '&';
                url += createString(object[name], name);
                count++;
            }
        }

        return url;
    };
})(jQuery);

Copy link

ghost commented May 20, 2014

$.parseParams('http://mysite.com/?form[name]=test'); // form[0].NaN = test

@Qantas94Heavy
Copy link

If this is used this in a project, do you have any licence or attribution requirements?

@sokool
Copy link

sokool commented Jan 22, 2015

@DimitryPHP have you solved that?

@kapoormanish
Copy link

Thanks Kares, it helps.

@scottwalters
Copy link

Using this to fake up a $.serializeObject() for want of one. There are serializeObject() implements, but the first code example here is small and easily pasted in-line.

        $('#create_account_form').on('submit', function(event) {
            event.preventDefault();
            $.ajax({
                'url': '/account/create',
                'method':'post',
                'data': $.parseParams( $('#create_account_form').serialize() ),

Thanks!

@geoidesic
Copy link

Yeah, the upgraded version doesn't work for me at all. Firstly it requires a leading "?" and I just get data[Nan]: "1". The original was better.

@bymaximus
Copy link

Solved data[NaN] problem, change line 51 from

params[key][parseInt(index)] = value;

To

params[key][index] = value;

@olaferlandsen
Copy link

dont work with more complex url, example:

https://gist.github.com/kares/956897?var[1]=0&var[2]=9&var[3][d]=f

Returns:

{
    "var" : {
         0 : "0" ,
         1 : "9",
         3 : "f"
    }
 }

Please check this function:

https://github.com/kvz/phpjs/blob/master/functions/strings/parse_str.js

@yairEO
Copy link

yairEO commented Oct 24, 2016

There is a larger debate going on here - http://stackoverflow.com/q/1131630/104380

@Tusko
Copy link

Tusko commented Feb 5, 2018

one line deParams :)

function deParams(str) {
    return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}

@CarabineSK
Copy link

PHPstorm inspection says this part is not quite ideal:
while ( e = re.exec(query) ) {
instead, it is better to use this:
while ((e = re.exec(query)) !== null) {

Same example in mozilla developer page: RegExp.prototype.exec()

@enniosousa
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment