Last active
January 28, 2023 03:06
-
-
Save emmaly/7d42ccc79dd5185fde1867a18420e634 to your computer and use it in GitHub Desktop.
URL + QueryString object converted to string
This file contains 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
/** | |
* @param {string} url | |
* @param {Object<string,string|string[]>} qs - query string | |
*/ | |
function urlWithQueryStringObject(url, qs) { | |
if (!qs) return url; | |
return [ | |
url, | |
Object.entries(qs) | |
.map(([k,v]) => { | |
if (Array.isArray(v)) { | |
return v | |
.map((v2) => [encodeURIComponent(k.trim()), encodeURIComponent(v2.toString().trim())].join("=")) | |
.join("&"); | |
} | |
return [encodeURIComponent(k.trim()),encodeURIComponent(v.toString().trim())].join("="); | |
}) | |
.join("&") | |
] | |
.join(/\?/.test(url) ? "&" : "?"); | |
} |
This file contains 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
function example() { | |
Logger.log( | |
urlWithQueryStringObject("list"), | |
); | |
Logger.log( | |
urlWithQueryStringObject("list?pageSize=9", { | |
pageToken: "pineapple", | |
}), | |
); | |
Logger.log( | |
urlWithQueryStringObject("list", { | |
pageToken: "pineapple", | |
pageSize: 18, | |
}), | |
); | |
Logger.log( | |
urlWithQueryStringObject("list", { | |
pageToken: "pineapple", | |
pageSize: [18,"tacos","99"], | |
}), | |
); | |
Logger.log( | |
urlWithQueryStringObject("list", { | |
pageToken: "pineapple", | |
pageSize: [18,"tacos","99"], | |
complication: { // not supported right now | |
color: "red", | |
}, | |
}), | |
); | |
Logger.log( | |
urlWithQueryStringObject("list", { | |
pageToken: "pineapple", | |
complication: { // not supported right now | |
color: ["red","yellow","green"], | |
}, | |
pageSize: [18,"tacos","99"], | |
}), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment