Sometimes you want to retrieve the URL query parameters when using JavaScript on the client side. JavaScript in the browser provides a global window.location
object providing you with all the URL parts. The query parameters are available in window.location.search
.
This tutorial shows you how to access and use the URL query parameters of the current website in client-side JavaScript.
JavaScript Series Overview
- Get the Current URL
- Get URL Query Parameters
- How to Smooth Scroll to an HTML Element
- Sort a Set
- New, Immutable Array Methods
- Detect Network Error
- Create Array from AsyncIterable
- Using the new Array Grouping Methods
- Test for LocalStorage Support
- Get Battery Status
- Detect If a Device Battery Is Charging
Retrieve the URL Query Parameters
You can access the raw query string of the current URL in JavaScript using the window.location.search
attribute:
const queryString = window.location.search
// '?filter=video&foo=bar'
If you want a brief overview of what
window.location
does, please have a look at our tutorial here on Future Studio on how to get the current URL.
You should know that accessing window.location.search
returns the raw query string including a leading ?
if query parameters are present. Here’s what you’re receiving:
- an empty string if the URL doesn’t carry query parameters
- a query string including a leading
?
if query parameters are present
You have to deal with the leading question mark ?
when query parameters are present on the current URL. This is tedious. The good news: all browsers come with a handy URLSearchParams
utility method to work with a URL query string.
Using Query Parameters With URLSearchParams
You can use the URLSearchParams utility within your browser to work with query parameters. You either pass the raw query string or an object as an argument to the method. The return value is a URLSearchParams
instance providing methods to interact with the data:
const params = new URLSearchParams(window.location.search)
Here’s an extensive code snippet with examples of how to interact with URLSearchParams
:
const params = new URLSearchParams('?filter=premium_tutorials&filter=premium_videos&page=3')
params.has('page') // true
params.has('filter') // true
[...params.keys()] // ['filter', 'filter', 'page']
[...params.values()] // ['premium_tutorials', 'premium_videos', '3']
[...params.entries()]
// [
// ['filter', 'premium_tutorials'],
// ['filter', 'premium_videos'],
// ['page', '3']
// ]
params.set('page', '10')
params.append('foo', 'bar')
params.toString()
// 'filter=premium_tutorials&filter=premium_videos&page=10&foo=bar&foo=bar'
Notice: the URLSearchParams#toString
method returns the query string without a leading ?
. You need to manually add it when you’re concatenating a query string onto an existing URL.
Enjoy!
Mentioned Resources
- How to get the current URL tutorial here on Future Studio
- MDN docs on
URLSearchParams