Created
December 18, 2012 04:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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