How to retrieve GET parameters from JavaScript ?
Last Updated :
12 Jan, 2023
In order to know the parameters, those are passed by the “GET” method, like sometimes we pass the Email-id, Password, and other details. For that purpose, We are using the following snippet of code.
When you visit any website, ever thought about what the question mark ‘?’ is doing in the address bar? Let’s find out what is the use of this question mark ‘?’.
What is the ‘?’:
The question mark acts like a separator and what follows after is a query string which is in the form of key-value pairs. Multiple key-value pairs are separated by the ‘&’ symbol.
Example:
geeksforgeeks.org/web-development?page=2&name=gfg
The above picture shows the address. The content followed by the ‘?’ is the query string which has two key-value pairs which are shown below :
- Pair 1: page = 2
- Pair 2: name = gfg
Our task is to get the respective values from each pair which are also known as GET parameters.
Approach 1: Using the keys specified in the address.
The class URLSearchParams takes in the address of the website and searches for the value associated with the key provided.
Example: Here is the code for the above approach:
Javascript
getParameter = (key) => {
address = window.location.search
parameterList = new URLSearchParams(address)
return parameterList.get(key)
}
console.log(getParameter( "ie" ))
|
Output:
2
Approach 2: Using the forEach property of the URLSearchParams class to retrieve all the GET parameters.
Example: This example shows the use of the above-explained approach.
Javascript
getParameters = () => {
address = window.location.search
parameterList = new URLSearchParams(address)
let map = new Map()
parameterList.forEach((value, key) => {
map.set(key, value)
})
return map
}
console.log(getParameters())
|
Output:
{"page" => "2", "name" => "gfg"}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...