# How to get all query string parameters as an object in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 22, 2020, updated Aug 8, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-convert-query-string-to-object

> Learn how to use the URLSearchParams interface to convert a query string into an object in JavaScript.

In JavaScript, you can use the `URLSearchParams` interface to convert a query string into an [object](https://attacomsian.com/blog/objects-prototypes-classes-javascript#objects). It provides utility methods to work with the query string of a URL.

1. Pass the query string to the `URLSearchParams` constructor to turn it into an object instance.
2. Use the `get()` method to [access query string parameters](https://attacomsian.com/blog/javascript-url-search-params).
3. To get a native JavaScript object, pass the object instance to the `Object.fromEntries()` method.

```javascript
const qs = `?size=M&price=29&sort=desc`

const params = new URLSearchParams(qs)

console.log(params.get('size')) // M
console.log(params.get('price')) // 29
console.log(params.get('sort')) // desc

// Convert to native JS object
const obj = Object.fromEntries(params)
console.log(obj)
// { size: 'M', price: '29', sort: 'desc' }
```

In the web browser, just pass `window.location.search` to the `URLSearchParams` constructor to turn the query string into an object:

```javascript
const params = new URLSearchParams(window.location.search)
```

If you have an entire URL, create a new [URL object](https://attacomsian.com/blog/javascript-url-object) to retrieve the query string, and then pass it to the `URLSearchParams` constructor:

```javascript
const url = new URL('http://example.com?size=M&price=29&sort=desc')

const params = new URLSearchParams(url.search)
```

The `Object.fromEntries()` function works fine as long as there are no duplicate query string parameters. If you have something like `?size=M&size=XL`, you'll only get `{ size: 'XL' }`.

To handle duplicate query string parameters, use the following approach instead:

```javascript
const qs = `?size=M&size=XL&price=29&sort=desc`

const params = new URLSearchParams(qs)

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

console.log(obj)
// { size: [ 'M', 'XL' ], price: '29', sort: 'desc' }
```

Read [this article](https://attacomsian.com/blog/javascript-convert-object-to-query-string-parameters) to learn how to convert an object to a query string in JavaScript.
