How to extract URL search parameters
Extracting a single parameter
If you require a one off extraction of a few parameters, this function will suffice.
function Param(a)
{
var m = location.search;
if (m && (m = m.match('[?&]' + a + '=([^&]*)')))
return decodeURIComponent(m[1]);
}
Extracting all parameters
This function extracts all the parameters into an object for easy access.
function Params()
{
var m = location.search, p = {}, i, n;
if (m && (m = m.match(/[?&][^=]*|=[^&]*/g)))
{
n = m.length;
for (i = 0; i < n; i += 2)
p[m[i].substr(1)] = m[i + 1] != '=' ? decodeURIComponent(m[i + 1].substr(1)) : '';
}
return p;
}
Example usage
<!DOCTYPE html>
<html>
<body>
<script>
function Param(a)
{
var m = location.search;
if (m && (m = m.match('[?&]' + a + '=([^&]*)')))
return decodeURIComponent(m[1]);
}
function Params()
{
var m = location.search, p = {}, i, n;
if (m && (m = m.match(/[?&][^=]*|=[^&]*/g)))
{
n = m.length;
for (i = 0; i < n; i += 2)
p[m[i].substr(1)] = m[i + 1] != '=' ? decodeURIComponent(m[i + 1].substr(1)) : '';
}
return p;
}
params = Params();
alert(
'def = "' + Param('def') + '"
' +
'bc = "' + params.bc + '"
' +
'z = "' + params.z + '"'
);
</script>
</body>
</html>
Launching the above code with a search string of ?a=1&bc=%2Fp%20%2Fq&def=p%26q%3F&y=&z=last will display:
def = "p&q?"
bc = "/p /q"
z = "last"