We can do it by some deferent way. Let see the bellow methods
let our current URL : https://devs3.pro/?email=mahabub%40exampla.com&phone=0897788665
Method 1: Using URLSearchParams and Object.fromEntries. It work in current all browser.
javascript
Object.fromEntries(new URLSearchParams(location.search))Output:
javascript
{email: 'mahabub@exampla.com', phone: '0897788665'}Method 2: Create a simple function as bellow -
javascript
function queryStringToObject(queryString) {
const pairs = queryString.substring(1).split('&');
// → ["foo=bar", "baz=buzz"]
var array = pairs.map((el) => {
const parts = el.split('=');
return parts;
});
// → [["foo", "bar"], ["baz", "buzz"]]
return Object.fromEntries(array);
// → { "foo": "bar", "baz": "buzz" }
}Call the function
javascript
queryStringToObject(location.search)Output :
javascript
{email: 'mahabub%40exampla.com', phone: '0897788665'}