I tried to implement a definitive, reliable URL query string parser that handles every corner case:
- it tries to be efficient by avoiding regex
- it takes full URLs or just query strings (as long as the query string begins with a question mark)
- it ignores the hash value
- it handles multiple equal parameter names
- it handles parameter names that equal built-in JavaScript methods and keywords
What do you think - did I miss something?
function parseURLParams(url) {
if (url === null) return;
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1);
if (query === url || query === "") return;
var params = {},
nvPairs = query.replace(/\+/g, " ").split("&");
for (var i=0; i<nvPairs.length; i++) {
var nv = nvPairs[i],
eq = nv.indexOf("=") + 1 || nv.length + 1,
n = decodeURIComponent( nv.slice(0, eq - 1) ),
v = decodeURIComponent( nv.slice(eq) );
if ( n !== "" ) {
if ( !Object.prototype.hasOwnProperty.call(params, n) ) {
params[n] = [];
}
params[n].push(v);
}
}
return params;
}
It returns an object of arrays for parsed URLs with query strings and undefined
if a query string could not be identified.
I used this in an answer over at SO.
[jquery]
tag. – Andy E Jun 13 '11 at 11:53+
on the entire string (which may be more efficient), and you've allowed for a string to be passed instead of using the current URL, but I can't spot any differences beyond those. I decided not to bloat my answer by supporting dupe parameters, as that practice is a rare one. However, I did link to a proof-of-concept example that would parse the URL in a similar style to how PHP would handle it. – Andy E Jun 13 '11 at 12:41window.location.search
and ignore duplicate params, your original version is fine, too. I was testing with full URLs; your key/value regex did not work with them. So, uhm... At least your approach could be more simplified (no nested functiond()
). :-P – Tomalak Jun 13 '11 at 13:06