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 deparamWritten by Jeremy
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Utility
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#