Open In App

How to get an object containing parameters of current URL in JavaScript ?

The purpose of this article is to get an object which contains the parameter of the current URL.

Example:



Input: www.geeksforgeeks.org/search?name=john&age=27
Output: { 
           name: "john", 
           age: 27
        }

Input: geeksforgeeks.org
Output: {}

To achieve this, we follow the following steps.

Example:






function getAllParams(url) {
  
    // Create an empty object
    let obj = {};
  
    // Extract the query params
    let paramsArray = url.match(/([^?=&]+)(=([^&]*))/g)
  
    // Check if there is one or more params
    if (paramsArray) {
  
        // Iterate the params array
        paramsArray.forEach((query) => {
  
            // Split the array
            let strings = query.split("=")
  
            // Assign the values to the object
            obj[strings[0]] = strings[1]
        })
    }
      
    // Return the object
    return obj;
}
  
console.log(getAllParams(
    "www.geeksforgeeks.org/search?name=john&age=27"))
console.log(getAllParams("geeksforgeeks.org"))

Output:

{
  age: "27",
  name: "john"
}

{}
Article Tags :