How do you get the query string values of the current page in JavaScript?
Topics
Web APIsJavaScript
在GitHub上编辑
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:
This will give you the value of the query parameter named key
.
How do you get the query string values of the current page in JavaScript?
Using URLSearchParams
The URLSearchParams
interface provides an easy way to work with query strings. Here's how you can use it:
- Create a
URLSearchParams
instance: Usewindow.location.search
to get the query string part of the URL. - Retrieve specific query parameters: Use the
get
method to get the value of a specific query parameter.
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: