Convert URL parameters to a JavaScript Object
Given an URL with parameters, The task is to get those parameters and convert them to a JavaScript Object using javascript. we’re going to discuss a few techniques.
Below is the following method to convert URL parameters to a JavaScript Object:
- Using replace() Method
- Using split() Method
- Using for …of loop
Method 1: Using replace() Method
This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.
Syntax:
string.replace(searchVal, newvalue)
Example: This example first takes the URL’s parameter portion and then uses the replace() method to form an object.
- Javascript
Javascript
console.log(search); search = search.split( '?' )[1]; function GFG_Fun() { console.log( '{"' + decodeURI(search) .replace(/"/g, '\\"' ).replace(/&/g, '","' ) .replace(/=/g, '":"' ) + '"}' ); } GFG_Fun() |
https://www.geeksforgeeks.org/?param_1=val_1&x=7&y=9 {"param_1":"val_1","x":"7","y":"9"}
Method 2: Using split() Method
This method is used to split a string into an array of substrings and returns the new array.
Syntax:
string.split(separator, limit)
Example: This example implements the same functionality but with a different approach. It first takes the parameter portion of the URL and then uses the replace() method to form an object.
- Javascript
Javascript
console.log(search); search = search.split( '?' )[1]; function GFG_Fun() { console.log( '{"' + search.replace(/&/g, '", "' ) .replace(/=/g, '":"' ) + '"}' , function (key, value) { return key === "" ? value : decodeURIComponent(value) }); } GFG_Fun() |
https://www.geeksforgeeks.org/?param_1=val_1&x=7&y=9 {"param_1":"val_1", "x":"7", "y":"9"} [Function (anonymous)]
Method 3: Using for …of loop
- In this we use Url.search for getting the parameters
- Now that passes as a parameter to the function
- Now use the for…of loop for accessing all keys and values
Example:
- Javascript
Javascript
function paramsToObject(params) { const obj = {}; const para = new URLSearchParams(params); for (const [key, value] of para) { if (obj.hasOwnProperty(key)) { if (Array.isArray(obj[key])) { obj[key].push(value); } else { obj[key] = [obj[key], value]; } } else { obj[key] = value; } } return obj; } const url = new URL(search); const params = paramsToObject(url.search); console.log(params); |
{ param_1: 'val_1', x: '7', y: '9' }