Skip to content
Related Articles

Related Articles

How to retrieve GET parameters from JavaScript ?
  • Last Updated : 31 Dec, 2020

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 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.

Method 1: Using the keys specified in the address: The class URLSearchParams takes in the address of the website and searches for value associated with the key provided.

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

Method 2: Using the forEach property of the URLSearchParams class to retrieve all the GET parameters.

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"}
My Personal Notes arrow_drop_up
Recommended Articles
Page :