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.
- Create an empty object.
- Using the String.match() method extract all the query params which are separated by ? and &, to achieve this we use the regex /([^?=&]+)(=([^&]*))/g
- The String.match() method returns an array containing all the queries.
- Using the for…each loop iterates the array and at every iteration split the value at = sign by using the String.split() method. This method returns an array of 2 strings the 0’th string is the left part of the = sign and the 1st string is the right part of the = sign.
- Assign the first string as the key and the second string as the value of that key in the newly created object.
- Finally, return the newly created object.
Example:
Javascript
<script> 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" )) </script> |
Output:
{
age: "27",
name: "john"
}{}