Get Query String Values with JavaScript URLSearchParams

01/22/2022
Contents
In this article, you will learn how to get query string values with JavaScript URLSearchParams.
Get Query String Values
Use the URLSearchParams method to get the value of the query string.
Below is a sample to get the keys and values from a URL with query parameters.
const url = new URL('https://plantpot.works?post=4665&action=edit');
const params = new URLSearchParams(url.search);
for(let param of params){
console.log(param);
}
//result
//["post", "4665"]
//["action", "edit"]
URLSearchParams.get()
It is also possible to get only the value by specifying the key with the URLSearchParams.get() method.
The URLSearchParams.get() method returns the value of the key that first matches the string specified in the argument.
const url = new URL('https://plantpot.works?post=4665&action=edit');
const params = new URLSearchParams(url.search);
console.log(params.get('post'));
console.log(params.get('action'));
//result
//"4665"
//"edit"
Methods of URLSearchParams
URLSearchParams has other useful methods such as:
Method | Description |
---|---|
URLSearchParams.append(key, value) | Add the key and value specified in the argument to the URL as a new search parameter |
URLSearchParams.delete(key) | Delete all keys and their values that match the specified key from the parameters |
URLSearchParams.entries() | Returns an iterator that enumerates the key / value pairs contained in the object |
URLSearchParams.forEach() | Returns all values contained in the object via a callback function |
URLSearchParams.get(key) | Returns the value of the first key that matches the key specified in the argument |
URLSearchParams.getAll(key) | Returns the values of all keys that match the key specified in the argument |
URLSearchParams.has(key) | Returns whether the key specified in the argument exists or a true/false value |
URLSearchParams.keys() | Returns an iterator that enumerates the keys contained in the object |
URLSearchParams.set(key, value) | Set the key and value specified in the argument to the parameter. If a value with the same name exists, it will be deleted |
URLSearchParams.sort() | Sort by the specified key |
URLSearchParams.toString() | Returns query parameters |
URLSearchParams.values() | Returns an iterator that enumerates the values of the keys contained in the object |