Get URL Variables in JavaScript & HTML

| Posted by watashii | Filed under Programming, Web

The 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'

Share:

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Print
  • email

Tags: , ,

One Response to “Get URL Variables in JavaScript & HTML”

  1. Greg Says:
    August 21st, 2009 at 7:56 pm

    Thanks dude! That tute solved a late introduced problem we needed to solve in order to release today :)

    Much obliged :)

Leave a Reply