Snippet: URL Parameters as Objects

Snippet

Back

URL Parameters as Objects

logo for JavaScript

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:

Loading...