-
-
Save cferdinandi/d173e6bcf8878a59b392b294ea911b5e to your computer and use it in GitHub Desktop.
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
<!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