The $.param( ) inverse function in JavaScript / jQuery

Viewed 87051

Given the following form:

<form>
    <input name="foo" value="bar">
    <input name="hello" value="hello world">
</form>

I can use the $.param( .. ) construct to serialize the form:

$.param( $('form input') )

=> foo=bar&hello=hello+world

How can I deserialize the above String with JavaScript and get a hash back?

For example,

$.magicFunction("foo=bar&hello=hello+world")

=> {'foo' : 'bar', 'hello' : 'hello world'}

Reference: jQuery.param( obj ).

18 Answers

This is a slightly modified version of a function I wrote a while ago to do something similar.

var QueryStringToHash = function QueryStringToHash  (query) {
  var query_string = {};
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    pair[0] = decodeURIComponent(pair[0]);
    pair[1] = decodeURIComponent(pair[1]);
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  } 
  return query_string;
};

Here's how you could create a new jQuery function:

jQuery.unparam = function (value) {
    var
    // Object that holds names => values.
    params = {},
    // Get query string pieces (separated by &)
    pieces = value.split('&'),
    // Temporary variables used in loop.
    pair, i, l;

    // Loop through query string pieces and assign params.
    for (i = 0, l = pieces.length; i < l; i++) {
        pair = pieces[i].split('=', 2);
        // Repeated parameters with the same name are overwritten. Parameters
        // with no value get set to boolean true.
        params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
            decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
    }

    return params;
};

This is really old question, but as i have coming - other people may coming to this post, and i want to a bit refresh this theme. Today no need to make custom solutions - there is URLSearchParams interface.

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

The only one limitation i know - this feature not supported in IE / Edge.

use this :

// convert query string to json object
var queryString = "cat=3&sort=1&page=1";

queryString
    .split("&")
    .forEach((item) => {
        const prop = item.split("=");
        filter[prop[0]] = prop[1];
    });

console.log(queryString);

Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests).

<button id='param'>GET</button> 
<div id="show"></div>
<script>
  $('#param').click(function () {
    var personObj = new Object();
    personObj.firstname = "vishal"
    personObj.lastname = "pambhar";
    document.getElementById('show').innerHTML=$.param(`personObj`));
  });
</script>
output:firstname=vishal&lastname=pambhar
Related