In vanilla 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.
Let us write a function that takes in a 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;
};
To use the above function in browsers, you can do the following:
parseParams(window.location.search);
Alternatively, you can create a new URL object to retrieve the query string, and pass it to the parseParams()
function:
// create new URL object
const url = new URL('http://example.com?size=M&size=XL&price=29&sort=desc');
// parse query parameters to object
console.log(parseParams(url.search));
You should see the following output:
{
"size": [
"M",
"XL"
],
"price": "29",
"sort": "desc"
}
Take a look at this article to learn more about how to convert an object to a query string in vanilla JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.