URL parameters as object

JavaScript, Browser, String, Regexp · Oct 22, 2020

Creates an object containing the parameters of the current URL.

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  );
getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript String Snippets

    Master string manipulation in JavaScript with this ES6 snippet collection.

    Collection · 108 snippets

  • Get base URL

    Gets the current URL without any parameters or fragment identifiers.

    JavaScript, String · Jan 3, 2021

  • How do I use JavaScript to modify the URL without reloading the page?

    Learn all of the options JavaScript provides for modifying the URL of the current page in the browser without reloading the page.

    JavaScript, Browser · Sep 27, 2021

  • Parse cookie

    Parses an HTTP Cookie header string, returning an object of all cookie name-value pairs.

    JavaScript, Browser · Oct 22, 2020