In an earlier article, 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:

// 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:

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

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

// 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 is available.

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

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.