JavaScript: Parsing URL parameters

Here's a nifty little JavaScript function that will read the URL of the the current page and return the value of a requested parameter:

// return a parameter value from the current URL
function getParam ( sname )
{
  var params = location.search.substr(location.search.indexOf("?")+1);
  var sval = "";
  params = params.split("&");
    // split param and value into individual pieces
    for (var i=0; i<params.length; i++)
       {
         temp = params[i].split("=");
         if ( [temp[0]] == sname ) { sval = temp[1]; }
       }
  return sval;
}

Given a URL something like "http://www.yoursite.com/app.asp?somevar=someval", you would call it like this:

function foo()
{
  var bar = getParam("somevar");
  alert(bar);
}

Merry scripting.
Tags: 

Comments

Works fine! Thanks!

Thanks dear...u r really genious...

Does the trick very neatly!

This doesn't handle when a query string doesn't have a value, it should then return `null`. It also doesn't handle `+` which means space.

See: https://github.com/sindresorhus/query-string

Thanks................
:)

So how would I go about printing the variable in an HTML form field as in this example:

You'd use the Document Object Model. Something like this:

oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = getParam("somevar");

http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml

Dan,

REAlly new to javascript.

I see this code of yours above:

Would you actually need to write two functions?

How would I get the value of ' bar ' into the input value of a field in a form?

For example here is the input line in the form:

I hope my questions are clear. %-)

Thank You,
Michelle

> Would you actually need to write two functions?

No. That just makes the first part reuasable. If you only need it to happen once, you can write it as one function.

> How would I get the value of ' bar ' into the input value of a field in a form?

Someone else asked about that, too. Look below at the comment titled "DOM".