Multiple ways to get query parameters in javascript


In this tutorial, Learn different ways to read query parameters in javascript

  • URLSearchParams

query parameters are key and value pairs added to url to pass the simple parameters

For example, if url is cloudhadoop.com/about?name=johh&dept=sales

query parameters are name=johh&dept=sales

In javascript , these are retrieved using

window.location.search  //name=johh&dept=sales
location.search // name=johh&dept=sales

window and location are global javascript object and window.location and location returns cloudhadoop.com/about

How to get query parameters for current URL

In latst browsers, we have URLSearchParams object used to get query parameters of a given URL.

you can check browser support here

let queryParams = new URLSearchParams(window.location.search);

let name = params.get("name"); // return john
let dept = params.get("dept"); // return sales

The same can also be rewritten using URL object with searchParams method which return URLSearchParams

let queryParams = (new URL(location.search)).searchParams;
let name = params.get("name"); // return john
let dept = params.get("dept"); // return sales

URLSearchParams support:

Plain Javascript code to get query parameters

Here is an utility function which is custom code returns query key and value pairs in javascript object.

  • Retrieved url query params string using window.location.search
  • Split string using = separatro
  • Iterate each property and separate key and value
function getQuerystring() {
    let output={}
    if(window.location.search){
    var queryParams = window.location.search.substring(1);
    var listQueries = queryParams.split("&");
        for(var query in listQueries) {
        if (listQueries.hasOwnProperty(query)) {
            var queryPair = listQueries[query].split('=');
            output[queryPair[0]] = decodeURIComponent(queryPair[1] || "");
        }
    }
    }
    return output;

Check query parameter exists

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.