How to Get Query String Values in JavaScript with URLSearchParams
Accessing and modifying query string values is a common task when working with web pages. In JavaScript, we can accomplish this using the URLSearchParams API, which is supported by all modern browsers.
Query Parameters in a URL
A query string is a part of a URL that follows the ?
symbol and contains key-value pairs. For example:
1 | https://test.com/hello?name=roger&age=20 |
In this case, we have two parameters: name
with a value of roger
, and age
with a value of 20
.
Accessing Query Parameters in JavaScript
To access the query parameters in a URL using JavaScript, we can create a new instance of the URLSearchParams object and pass the query string part of the URL to it. We can obtain the query string using window.location.search
. Here is an example:
1 | const params = new URLSearchParams(window.location.search); |
Now, we can perform various operations on the params
object to retrieve and manipulate the query parameters.
Retrieving Query Parameters
We can check if a parameter exists by using the has
method:
1 | params.has('test'); |
To get the value of a parameter, we can use the get
method:
1 | params.get('test'); |
If a parameter can have multiple values, we can use the getAll
method to retrieve an array containing all the values:
1 | params.getAll('name'); |
Iterating Over Query Parameters
To iterate over all the query parameters, we can use a for...of
loop:
1 | for (const param of params) { |
Alternatively, we can use other methods provided by the URLSearchParams API:
forEach
- Iterates over the parameters.entries
- Returns an iterator containing the key/value pairs of the parameters.keys
- Returns an iterator containing the keys of the parameters.values
- Returns an iterator containing the values of the parameters.
Modifying Query Parameters
The URLSearchParams API also provides methods to modify the query parameters without changing the URL itself:
append
- Appends a new parameter to the object.delete
- Deletes an existing parameter.set
- Sets the value of a parameter.
We can use these methods to update the query string and generate a new one using the toString
method.
Conclusion
In this article, we learned how to access and modify query string values in JavaScript using the URLSearchParams API. This API provides a convenient way to work with query parameters and perform various operations on them. Remember to test your code across multiple browsers to ensure compatibility.
Tags: JavaScript, query string, URLSearchParams, web development