Monday 28 July 2008

Get URL Parameters Using Javascript

Most URL parameters are read and processed by server side code, however you can access them easily by using Javascript. Add the function from this example to your page and call it, passing it the parameter name you want to read.

<html>
<head>
<script>
function getParam(name)
{
var start=location.search.indexOf("?"+name+"=");
if (start<0)
start=location.search.indexOf("&"+name+"=");
if (start<0)
return '';
start += name.length+2;
var end=location.search.indexOf("&",start)-1;
if (end<0)
end=location.search.length;
var result=location.search.substring(start,end);
var result='';
for(var i=start;i<=end;i++)
{
var c=location.search.charAt(i);
result=result+(c=='+'?' ':c);
}
return unescape(result);
}
</script>
</head>
<body>
<script>
document.write(getParam("test1")+"<br>");
document.write(getParam("test2")+"<br>");
</script>
</body>
</html>

So to test the code call it up in your browser and add the following to the end of the URL in the address bar.

?test1=Hello&test2=World

The test page will then display the parameter values

....Done.

No comments: