parseStr functions similarly to parse_str (PHP). It takes a query string as an argument and returns the contained parameters as properties of an object.
Kudos to Uwe “e-voc” Pries for his implementation idea.
/**
* function parseStr
* Copyright (C) 2006 Dao Gottwald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact information:
* Dao Gottwald <dao at design-noir.de>
* Herltestraße 12
* D-01307, Germany
*
* @version 1.2
* @url http://design-noir.de/webdev/JS/parseStr/
*/
function parseStr(s) {
var rv = {}, decode = window.decodeURIComponent || window.unescape;
(s == null ? location.search : s).replace(/^[?#]/, "").replace(
/([^=&]*?)((?:\[\])?)(?:=([^&]*))?(?=&|$)/g,
function ($, n, arr, v) {
if (n == "")
return;
n = decode(n);
v = decode(v);
if (arr) {
if (typeof rv[n] == "object")
rv[n].push(v);
else
rv[n] = [v];
} else {
rv[n] = v;
}
});
return rv;
}
// let's pretend the document's URL is http://example.com/path/file?param1=x¶m2=y#a=foo&b=bar
var args = parseStr(location.search); // {param1:"x", param2:"y"}
args.param1; // "x"
parseStr(); // {param1:"x", param2:"y"} (parseStr parses location.search by default)
parseStr(location.hash); // {a:"foo", b:"bar"}
parseStr('foo=1%202&bar[]=x&&baz&bar[]=y'); // {foo:"1 2", bar:["x", "y"], baz:""}