How to get URL parameters using JavaScript

Here’s a simple JavaScript function that will return URL parameter values.

// returns the parameter value from the url that matches the key
// if the parameter doesn't exist, returns an empty string
function getQuerystring(key, defaultVal)
{
   if (defaultVal == null){
       defaultVal = "";
   }
   key = key.replace(/[[]/,"\[").replace(/[]]/,"\]");
   var regex = new RegExp("[\?&]"+key+"=([^&#]*)");
   var result = regex.exec(window.location.href);

   if (result == null){
      return defaultVal;
   } else {
      return result[1];
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s