JavaScript Get URL Parameters

  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

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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.