How to Get URL Parameters in JavaScript

Harshit Jindal Feb 02, 2024
  1. Use URL Object’s searchParams to Get the Values From the GET Parameters
  2. Use location.search to Get the Values From the GET Parameters
How to Get URL Parameters in JavaScript

This tutorial teaches how to get the values from the GET parameters.

Use URL Object’s searchParams to Get the Values From the GET Parameters

The URL object represents the URL defined by the parameters. We can use its searchParams property to return a URLSearchParams object that allows us to access the parameters decoded in GET. We can then use the get function attached to the URLSearchParams object to get the value of any parameter inside the URL.

var input_string =
    'http://www.google.com/app.html?apple=1&banana=3&cherry=m2';  // window.location.href
var url = new URL(input_string);
var cherry = url.searchParams.get('cherry');
console.log(cherry);

In the above code, we first get the URLSearchParams object and then use its get function to get decoded parameter values.

Use location.search to Get the Values From the GET Parameters

The search property of location is basically a search string that is also called query string. To get the values of parameters, we split the string and then store the parameters and their values in a dictionary. We can then easily use the dictionary to get all key and value pairs.

var GET_parameters = {};

if (location.search) {
  var splitts = location.search.substring(1).split('&');
  for (var i = 0; i < splitts.length; i++) {
    var key_value_pair = splitts[i].split('=');
    if (!key_value_pair[0]) continue;
    GET_parameters[key_value_pair[0]] = key_value_pair[1] || true;
  }
}

var abc = GET_parameters.abc;

All the methods discussed are supported by all the major browsers.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn