24 Jun
Query String to Object via regex
Just sharing a nice little code snippet that makes use of regular expressions instead of loops for converting.
function getQuery(s) {
var query = {};
s.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {
if (typeof query[a] != 'undefined') {
query[a] += ',' + d;
} else {
query[a] = d;
}
});
return query;
}
// usage:
// var o = getQuery('maps.google.co.uk/maps?f=q&q=brighton&ie=UTF8&iwloc=addr');
// console.dir(o);
Note that if a query string key is found more than once, it's value is appended. If you don't want this functionality, remove the test for undefined.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)
Hi Remy, very well done.
One question, what are the 'b's for ? did you mean '\b'.
I don't think you even need those \b's.
Cheers mate
@Ariel - damn escaping - they were supposed to be
\bindicating a break...that said you're right, they may not even bee required.[...] would then pass that in to my getQuery function so I had access to it as an [...]