# How to get query string parameters in JavaScript

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

> A quick guide to learn how to get query string parameters from the current browser URL by using vanilla JavaScript.

In an [earlier article](https://attacomsian.com/blog/javascript-url-search-params), we looked at how to add or update query string parameters using `URLSearchParams` in JavaScript. Today, you'll learn how to get query string parameters from the URL in JavaScript.

To get the query string from the current browser URL, you can use `window.location.search`:

```javascript
// URL: http://example.com?size=M&size=XL&price=29&sort=desc

console.log(window.location.search)
// ?size=M&size=XL&price=29&sort=desc
```

To create an instance of `URLSearchParams`, pass the full query string to its constructor:

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

The `URLSearchParams` provides several methods that you can use to manipulate query string parameters:

```javascript
// get parameter
params.get('price') // 29

// get multi-valued parameter
params.getAll('size') // [ 'M', 'XL' ]

// check if parameter exists
params.has('sort') // true

// iterate over all parameters
for (const p of params) {
  console.log(p)
}

// [ 'size', 'M' ]
// [ 'size', 'XL' ]
// [ 'price', '29' ]
// [ 'sort', 'desc' ]
```

While `URLSearchParams` is an ideal solution to work with query strings, it is not supported by all browsers. If you want to support old browsers like Internet Explorer, a [polyfill](https://github.com/ungap/url-search-params) is available.

Alternatively, you could write your own JavaScript function that takes in a query string parameter name and returns its value:

```javascript
function queryParam(name) {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
  var results = regex.exec(window.location.search)
  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
}

queryParam('price') // 29
queryParam('sort') // desc
```
