How To Read URL Parameters Using JavaScript

          Reading URL parameters using JavaScript is not as easy as using simple syntax in PHP or in some other server side scripting languages. We need to read the URL, Save it in a variable and further process is required to get parameters from the URL.          First, we need to get the current browser location which is the required URL.

window.location.href

We are going to use “split” syntax to split the URL into host name as the first variable and parameters as the second variable and if the size of second variable is greater than 0, then we go to further process.

var url = window.location.href;
if( url.indexOf(‘?’) != -1 && url.split(‘?’)[1].length > 1)
{
  //***Further Process***//
}
else
{
  document.write(“No Parameters Found”);
}

If the above condition is satisfied, we need to process to get parameters, else we need to display a message saying “no parameters found”. Further process includes splitting “&” and storing the values of the respected parameter.

var url = window.location.href;
if( url.indexOf(‘?’) != -1 && url.split(‘?’)[1].length > 1)
{
 url = url.split(‘?’);
 terms = url[1].split(“&”);
 for(var i = 0; i < terms.length; i++)
 {
  document.write(“Parameter “+i+” is: “+terms[i].split(‘=’)[1]);
 }
}
else
{
  document.write(“No Parameters Found”);
}

By the above way you can display the parameters or you can use them for your further process.

Leave a Reply

Your email address will not be published. Required fields are marked *