Snippet
Back
URL Parameters as Objects

Creates an object containing the parameters of the current URL.
// add the function
const getURLParameters = (url) =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
)
// call the function
getURLParameters(window.location.toLocaleString())
// example
getURLParameters('http://example.com/page?id=1234&name=Bob');
// {id: '1234', name: 'Bob'}
The above is just a simple example of getting the URL parameters and returning them as an object. In this example we are:
- Use String.prototype.match() with an appropriate regular expression to get all key-value pairs.
- Use Array.prototype.reduce() to map and combine them into a single object.
- Pass window.location.toLocaleString() as the argument to apply to the current url.