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
function getAllParams(url) {
let obj = {};
let paramsArray = url.match(/([^?=&]+)(=([^&]*))/g)
if (paramsArray) {
paramsArray.forEach((query) => {
let strings = query.split( "=" )
obj[strings[0]] = strings[1]
})
}
return obj;
}
console.log(getAllParams(
"www.geeksforgeeks.org/search?name=john&age=27" ))
console.log(getAllParams( "geeksforgeeks.org" ))
|
Output:
{
age: "27",
name: "john"
}
{}