Snippet: URL Parameters as Objects

Snippet

Back

URL Parameters as Objects

logo for JavaScript

Creates an object containing the parameters of the current URL.

1// add the function
2const getURLParameters = (url) =>
3  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
4    (a, v) => (
5      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
6    ),
7    {}
8  )
9  
10// call the function
11getURLParameters(window.location.toLocaleString())
12 
13// example
14getURLParameters('http://example.com/page?id=1234&name=Bob');
15// {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: