Tuesday, September 19, 2006

A simple Javascript function to get URL parameters


Most of the server-side programming languages that I know of like PHP, ASP, or JSP give you easy access to parameters in the query string of a URL. Javascript does not give you easy access. With javascript you must write your own function to parse the window.location.href value to get the query string parameters you want. Here is a small function I wrote that will parse the window.location.href value and return the value for the parameter you specify. It does this using javascript's built in regular expressions. Here is the function:

function gup( name )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

The way that the function is used is fairly simple. Let's say you have the following URL:

http://www.foo.com/index.html?bob=123&frank=321&tom=213#top

You want to get the value from the frank parameter so you call the javascript function as follows:

var frank_param = gup( 'frank' );

Now if you look at the frank_param variable it contains the number 321. The query string was parsed by the regular expression and the value of the frank parameter was retrieved. The function is smart in a couple of ways. For example, if you have an anchor in your URL like our example URL above does (#top) the gup() function knows to stop before the # character. Also, if a requested parameter doesn't exist in the query string then an empty string is returned instead of a null.

Get more information

Tags: javascript, url parameters, get url parameters, server side, window.location.href, javascript function