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()
|
Output
https://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()
|
Output
https://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' }
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
26 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...