Last active
November 14, 2018 19:07
-
-
Save jimmielemontgomery/e9c37ae9a3ce595b2fea2e67276ab3d1 to your computer and use it in GitHub Desktop.
URL composition related
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
https://developer.mozilla.org/en-US/docs/Web/API/URL | |
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams | |
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch | |
https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en | |
var url = new URL(location.hash.replace(/^#/,''), location.origin); | |
url.searchParams.set('x',1234) | |
url.search | |
"?x=1234" | |
// multiple x | |
url.searchParams.append('x',567) | |
// new y | |
url.searchParams.append('y',101) | |
url.search | |
"?x=1234&x=567&y=101" | |
// overwrite all the x entries: | |
url.searchParams.set('x',44) | |
url.search | |
"?x=44&y=101" | |
url.searchParams.delete('x') | |
url.search | |
"?y=101" | |
// direct assignment | |
url.search = | |
"?x=1234&x=567&y=101" | |
url.search | |
"?x=1234&x=567&y=101" | |
Array.from(url.searchParams.keys()) | |
(3) ["x", "x", "y"] | |
url.toString() | |
"http://localhost/things?x=1234&x=567&y=101" | |
location.hash = url.pathname + url.search | |
location.hash | |
"#/things?x=1234&x=567&y=101" | |
fetch(url.pathname, { | |
method: 'POST', | |
headers: new Headers({ | |
"Content-type": "application/x-www-form-urlencoded" | |
//"application/json; charset=utf-8" "multipart/form-data" "application/x-www-form-urlencoded" | |
}), | |
// same format as GET url search params a&b&c | |
body: url.searchParams | |
}).then((res)=>{ console.log(res); return res }).catch((res)=>{ console.warn(res); return res; }); | |
// note automatic encoding of emoji and what typically is done via encodeURIComponent: | |
Object.entries({a:1,b:"🍻",c:'"stuff&things"'}).forEach(url.searchParams.set, url.searchParams); | |
url.search; | |
"?a=1&b=%F0%9F%8D%BB&c=%22stuff%26things%22" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment