Created
March 26, 2021 11:29
-
-
Save yavgel85/8472a81e07032176ce2e29bcaed9ce4b to your computer and use it in GitHub Desktop.
getURLParameters #js #browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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