;

How to Get Query String Parameters as an Object in Javascript


Tutorialsrack 19/03/2022 Jquery Javascript

In this article, you’ll learn how to get query string parameters as an object in Javascript. In JavaScript, there is no direct way to convert a query string into an object. However, you can use the URLSearchParams interface to parse a query string and then iterate over all keys to create an object.

Here is a function that takes query string as a parameter and returns an object of all query string parameters:

const parseParams = (querystring) => {
    // parse query string
    const params = new URLSearchParams(querystring);

    const obj = {};

    // iterate over all keys
    for (const key of params.keys()) {
        if (params.getAll(key).length > 1) {
            obj[key] = params.getAll(key);
        } else {
            obj[key] = params.get(key);
        }
    }

    return obj;
};

You can use the above function in browsers as given below:

parseParams(window.location.search);

Alternatively, you can also create a new URL object to retrieve the query string, and pass it to the parseParams() function, as given below example:

// create new URL object
const url = new URL('http://example.com?size=M&size=XL&price=900&sort=desc');

// parse query parameters to object
console.log(parseParams(url.search));
//Output
[object Object] {
  price: "900",
  size: ["M", "XL"],
  sort: "desc"
}

I hope this article will help you to understand how to get query string parameters as an object in Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags