How do you get the query string values of the current page in JavaScript?
Topics
Web APIsJavaScript
TL;DR
To get the query string values of the current page in JavaScript, you can use the URLSearchParams object. First, create a URLSearchParams instance with window.location.search, then use the get method to retrieve specific query parameters. For example:
Using URLSearchParams
The URLSearchParams interface provides an easy way to work with query strings. Here's how you can use it:
- Create a
URLSearchParamsinstance: Usewindow.location.searchto get the query string part of the URL. - Retrieve specific query parameters: Use the
getmethod to get the value of a specific query parameter.
If the query parameter does not exist, the get method returns null.
Example
Consider a URL like https://example.com?page=2&sort=asc. To get the values of page and sort:
Handling multiple values
If a query parameter appears multiple times, you can use the getAll method to retrieve all values:
Checking for the existence of a parameter
You can use the has method to check if a query parameter exists.
Iterating over all parameters
You can iterate over all query parameters using the forEach method:
Further reading
- MDN Web Docs: URLSearchParams
- MDN Web Docs: window.location
- Practice 190+ JavaScript interview questions on GitHub
Exercises
Check your understanding
Beta