Get URL Variables in JavaScript & HTML
| Posted by watashii | Filed under Programming, WebThe following structure stores variables within a request URL:
http://www.mydomain.com/index.html?month=January&day=Tuesday
To read the variables within the index HTML file, we must process the URL string entirely, since there is no built-in functions which magically does it. The following JavaScript demonstrates this:
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
To use the variables, we run the following to extract the values:
var myHash = getUrlVars();
alert(myHash['month']); // prompts the value 'January'
alert(myHash['day']); // prompts the value 'Tuesday'
Tags: html, javascript, url
One Response to “Get URL Variables in JavaScript & HTML”
-
Greg Says:
August 21st, 2009 at 7:56 pmThanks dude! That tute solved a late introduced problem we needed to solve in order to release today :)
Much obliged :)