Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Created December 18, 2012 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bollwyvl/4325043 to your computer and use it in GitHub Desktop.
Save bollwyvl/4325043 to your computer and use it in GitHub Desktop.
Parse up some URL arguments into an associative array. Won't handle same-name checkboxes, i.e. x=1&x=2, but could be extended to do so... jsperf says the while loop is usually fastest. http://jsperf.com/url-get-string-parsing
var re = new RegExp("([^?=&]+)(=([^&]*))?", "g");
function with_regex(url){
var args = {};
url.replace(re, function($0, $1, $2, $3) {
args[$1] = $3;
});
return args
}
function with_reduce(url){
return url.split("&").reduce(function(res, bit){
bit = bit.split("=");
res[bit[0]] = bit[1];
return res;
}, {});
}
function with_forloop(url){
var args = {},
str_split = url.split("&"),
i, kv;
for(i = str_split.length; i; i--){
kv = str_split[i-1].split("=");
args[kv[0]] = kv[1];
}
return args;
}
function with_while(url){
var args = {},
str_split = url.split("&"),
i = str_split.length,
kv;
while(i--){
kv = str_split[i].split("=");
args[kv[0]] = kv[1];
}
return args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment