[フレーム]
Last Updated: February 25, 2016
·
7.697K
· zaus

deparam function in JavaScript - opposite of $.param

A little bit cleaner on JSFiddle - http://jsfiddle.net/drzaus/8EE8k/

Often in Javascript you want to parameterize a map (hash|dictionary|whatever) to create a URL string, and jQuery has the utility function $.param to help you do so:

var urlQueryString = $.param({
 action: "create",
 what: "ProductEntry",
 color: "green",
 size: "medium"
});

yields

action=create&what=ProductEntry&color=green&size=medium

But what happens when you want the reverse? jQuery doesn't have a "deparam" function. I bet other utility libraries do, and are probably more robust, but it's fun to write your own.

deparam = function (querystring) {
 // remove any preceding url and split
 querystring = querystring.substring(querystring.indexOf('?')+1).split('&');
 var params = {}, pair, d = decodeURIComponent, i;
 // march and parse
 for (i = querystring.length; i > 0;) {
 pair = querystring[--i].split('=');
 params[d(pair[0])] = d(pair[1]);
 }

 return params;
};//-- fn deparam

AltStyle によって変換されたページ (->オリジナル) /