How to get the parameters from a URL in JavaScript

Let's assume that we want to read the parameters of the following URL:

https://erikmartinjordan.com?name=Erik&city=Barcelona

The aim is to assign them to an object:

javascript
// Reading the full URL
// https://erikmartinjordan.com?name=Erik&city=Barcelona
let url = window.location.href;

// Getting the string after the '?'
// 'name=Erik&city=Barcelona'
let str = url.split('?')[1];

// Splitting the string if '&'
// ['name=Erik', 'city=Barcelona']
let arr = str.split('&');

// Resplitting every string of the array if '='
// [['name', 'Erik'], ['city', 'Barcelona']]
let entries = arr.map(str => [str.split('=')[0], str.split('=')[1]]);

// Transforming array of arrays into an object
let object = Object.fromEntries(entries);

console.log(object);
//{name: "Erik", city: "Barcelona"}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.