Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 18:04
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 cferdinandi/ed47e91d50dca8377754a721ae77a76b to your computer and use it in GitHub Desktop.
Save cferdinandi/ed47e91d50dca8377754a721ae77a76b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>getParams()</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
/**
* Get the URL parameters
* (c) Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {String} url The URL
* @return {Object} The URL parameters
*/
function getParams (url = window.location) {
let params = {};
new URL(url).searchParams.forEach(function (val, key) {
if (params[key] !== undefined) {
if (!Array.isArray(params[key])) {
params[key] = [params[key]];
}
params[key].push(val);
} else {
params[key] = val;
}
});
return params;
}
let url = 'https://gomakethings.com?sandwhich=chicken%20salad&bread=wheat&topping=tomato&topping=spicy+mayo';
let params = getParams(url);
console.log(params);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment