QueryString – get parameters from URL with JavaScript

July 23rd, 2007 | Categories: JavaScript, SharePoint

SharePoint passes a lot of information between pages with the aid of URL parameters. If you pay attention to the URL while watching the EditForm of some list, you’ll probably find the folloring url:

http://server/site/lists/listname/EditForm.aspx?ID=1&Source=http://server/site/lists/listname/Allitems.aspx

The part after the question mark is important, since it’s passing 2 parameters: ID with value of 1 and Source with value of http://server/site/lists/listname/Allitems.aspx.

Using XSLT with SharePoint Designer you can also get these parameters with XSLT’s QueryString. But outside of a SharePoint Data View you can get the value of URL’s parameters with the following script:

function queryString(parameter) { 
  var loc = location.search.substring(1, location.search.length);
  var param_value = false;

  var params = loc.split(“&”);
  for (i=0; i      param_name = params[i].substring(0,params[i].indexOf(‘=’));
      if (param_name == parameter) {
          param_value = params[i].substring(params[i].indexOf(‘=’)+1)
      }
  }
  if (param_value) {
      return param_value;
  }
  else {
      return false;
//Here determine return if no parameter is found
  }
}

So if I had my page http://www.mysite.com/default.aspx?test=123

The queryString(‘test’) would return value 123.

This function is useful also outside of SharePoint. One word of caution though: Internet Explorer tends to translate a bit the urls, so spaces become %20 and similar. This can be solved with a simple function to translate these values. More about that – next time 🙂