Aug

8

Get Value of URL Parameters using JavaScript

Posted by Leave a Comment

If you are looking for a quick and easy way to grab the value of a query string parameter from a URL, you only need a few lines of JavaScript. The below script will return the value of the matching parameter or return false if no match was found.

function getParameter(theParameter) { 
  var params = window.location.search.substr(1).split('&');
 
  for (var i = 0; i < params.length; i++) {
    var p=params[i].split('=');
	if (p[0] == theParameter) {
	  return decodeURIComponent(p[1]);
	}
  }
  return false;
}

The decodeURIComponent() function ensures that any values such as http%3A%2F%2Ftechnicaloverload.com%2F are returned correctly: http://technicaloverload.com/

So using the example:
http://technicaloverload.com?test1=yes&test2=no&test3=http%3A%2F%2Ftechnicaloverload.com%2F

we get the following results:

getParameter('test1') --> yes
getParameter('test2') --> no
getParameter('test3') --> http://technicaloverload.com/
getParameter('test4') --> false

Note that this a very basic script intended as an example to get you started. It provides no validation outside of returning false if no matching parameter was found.

Category: Development, JavaScript, Web Development

Leave a Reply