Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/8472a81e07032176ce2e29bcaed9ce4b to your computer and use it in GitHub Desktop.
Save yavgel85/8472a81e07032176ce2e29bcaed9ce4b to your computer and use it in GitHub Desktop.
getURLParameters #js #browser
// Creates an object containing the parameters of the current URL.
// 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 location.search as the argument to apply to the current url.
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
);
// Examples
getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment