Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 18:05
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/d173e6bcf8878a59b392b294ea911b5e to your computer and use it in GitHub Desktop.
Save cferdinandi/d173e6bcf8878a59b392b294ea911b5e to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>getParam()</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
/**
* Get the value of a query string from a URL
* (c) Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {String} param The parameter to get the value of
* @param {String} url The URL to get the value from [optional]
* @return {String} The value
*/
function getParam (param, url = window.location) {
let params = new URL(url).searchParams;
let val = params.getAll(param);
if (val.length > 1) return val;
return val[0];
}
let url = 'http://example.com?this=chicken&that=sandwich&topping=tomato&topping=spicy+mayo';
// returns "chicken"
let thisOne = getParam('this', url);
console.log(thisOne);
// returns "sandwich"
let thatOne = getParam('that', url);
console.log(thatOne);
// returns "tomato"
let topping = getParam('topping', url);
console.log(topping);
// returns "spicy mayo"
let anotherOne = getParam('another', url);
console.log(anotherOne);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment