Open In App
Related Articles

How to retrieve GET parameters from JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

// Arrow function to get the parameter
// of the specified key
getParameter = (key) => {
  
    // Address of the current window
    address = window.location.search
  
    // Returns a URLSearchParams object instance
    parameterList = new URLSearchParams(address)
  
    // Returning the respected value associated
    // with the provided key
    return parameterList.get(key)
}
  
// Gets the value associated with the key "ie"
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

// Arrow function to get all the GET parameters
getParameters = () => {
  
    // Address of the current window
    address = window.location.search
  
    // Returns a URLSearchParams object instance
    parameterList = new URLSearchParams(address)
  
    // Created a map which holds key value pairs
    let map = new Map()
  
    // Storing every key value pair in the map
    parameterList.forEach((value, key) => {
        map.set(key, value)
    })
  
    // Returning the map of GET parameters
    return map
}
  
// Gets all the getParameters
console.log(getParameters())

                    

Output:

{"page" => "2", "name" => "gfg"}


Last Updated : 12 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads