Fetch query string parameters from url in javascript

You may familiar to retrieve query string parameters in any server side language like php.

Let the url is

coderexample.html?post_id=239&category=Angular

if you want to get 239 from above url you can easily write $_GET[‘post_id’] or something like $_REQUEST[‘post_id’].

You can also get category Angular using $_GET[‘category’]/$_REQUEST[‘category’].

In this tutorial, I will show how to fetch query string parameters ie, id & category from above url using javascript.

Fetch query string parameter from url in javascript

Step1: Get current url

window.location.href; // coderexample.html?post_id=239&category=Angular

Step2: get “?” position and slice the remaining part from the url

window.location.href.slice(window.location.href.indexOf('?') + 1) // post_id=239&category=Angular

Step3: convert to an array

var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
// ["id=239", "category=Angular"]

Step4: Push in a new array according to index and value by slicing “=”

var params;
for (var i=0;i<url.length;i++) {
    params = url[i].split("=");
}

console.log(params[0]); //239
console.log(params[1]); //Angular

So we have extracted the parameters. Let’s create a generalized function, so we can fetch value by index.

function getParam(param) {
  var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for (var i=0;i<url.length;i++) {
         var params = url[i].split("=");
         if(params[0] == param)
          return params[1];
  }
  return false;
}

Now you can get value simply calling getParam() function by index.

getParam("id") // 239
getParam("category") // 239

DownloadDemo


  • Soumik Bose

    Useful tricks Arka.