Update: here's the article I wrote about it one time for HTML Goodies: http://www.htmlgoodies.com/beyond/javascript/article.php/11877_3755006_2
Take a look at the simple ptq
(parse-the-query) function, one of the library of functions I wrote in 2001.
function ptq(s, q) {
var i, p;
s = s.replace(/\+/g, ' ').replace(/;/g, '&').split('&');
q = q || {};
for (i=0; i<s.length; i++) {
p = s[i].split('=', 2);
q[unescape(p[0])] = unescape(p[1]);
}
return q;
}
It works even with very old JavaScript versions, and using it is simple:
var q = ptq(location.search.substring(1));
/* grab query string after the initial "?" delimiter */
The properties of q
will then correspond to any name=value
pairs defined in the HTML form values submitted to the current URL via a GET request's query string.
For example, if an HTML form contained a field named name
with contents "Joseph" and if this form is submitted as specified by its action
attribute to the HTML page file.html
then the GET request will be "file.html?name=Joseph" and the value of q.name
will equal the string literal "Joseph"
.
Some parts of the code, like escape
/unescape
have newer and preferred equivalents if later features of JavaScript are available.
Dredging up a later revision of this code, you can also use Boolean parameters in your URLs like "file.html?name=Joseph&secure", although these will never be generated by a browser when submitting an HTML form. It's also easier to use. Just write q = param();
in your code, similar to Lincoln D. Stein's CGI.pm module syntax.
function ptq(q)
{
/* parse the query */
/* semicolons are nonstandard but we accept them */
var x = q.replace(/;/g, '&').split('&'), i, name, t;
/* q changes from string version of query to object */
for (q={}, i=0; i<x.length; i++)
{
t = x[i].split('=', 2);
name = unescape(t[0]);
if (!q[name])
q[name] = [];
if (t.length > 1)
{
q[name][q[name].length] = unescape(t[1]);
}
/* next two lines are nonstandard */
else
{
q[name][q[name].length] = true;
}
}
return q;
}
function param()
{
return ptq(location.search.substring(1).replace(/\+/g, ' '));
}
Note that in this new revision all form fields are returned as arrays. This is much more appropriate since the standard allows for multiple form fields with the same name, meaning that the correct the data type for a form field's value is an array of strings.