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
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
console.log(search);
search = search.split( '?' )[1];
function GFG_Fun() {
console.log( '{"' + decodeURI(search)
.replace(/"/g, '\\"' ).replace(/&/g, '","' )
.replace(/=/g, '":"' ) + '"}' );
}
GFG_Fun()
|
Outputhttps://www.geeksforgeeks.org/?param_1=val_1&x=7&y=9
{"param_1":"val_1","x":"7","y":"9"}
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
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()
|
Outputhttps://www.geeksforgeeks.org/?param_1=val_1&x=7&y=9
{"param_1":"val_1", "x":"7", "y":"9"} [Function (anonymous)]
- 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
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);
|
Output{ param_1: 'val_1', x: '7', y: '9' }