How To Get Url Parameters Using Javascript

Here, I am going to share Javascript code to get the URL querystring parameter values.

Let me take a sample URL and try to get the parameter values in it.

http://www.techtricky.com?id=77&name=sree

Here is the function to create the Javascript object with parameter names and values.

 
function getUrlParams() {
  var params = {};
  window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
    params[key] = value;
  });

  return params;
}

In the above code, “window.location.search” is to get the query string, “replace” function and regular expression is to parse and save the parameters in the object.

Get the variables by calling above function:

 
var params = getUrlParams();
alert(params.id);
alert(params.name);

Sometimes you might need to access the hash variables in the URL, below is the code for that:

 
var hash = window.location.hash;

Below is the code to set the hash variable for existing URL:

 
window.location.hash = "#top";
5 Comments

Add a Comment

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

Close Bitnami banner