Skip to content

Instantly share code, notes, and snippets.

@caomingkai
Created August 28, 2019 06:59
Show Gist options
  • Save caomingkai/966201a7c6741cf7d91eeb3907268867 to your computer and use it in GitHub Desktop.
Save caomingkai/966201a7c6741cf7d91eeb3907268867 to your computer and use it in GitHub Desktop.
URL-query-parser
// query parser
function URL_query_parser(url) {
let urlObj = null;
let res = new Map();
try {
urlObj = new URL(url);
const searchParams = urlObj.searchParams;
console.log({searchParams})
searchParams.forEach((value, key, map) => {
res[key] = value;
});
console.log(res);
return res;
} catch(e) {
console.log("Invalide URL", e)
}
}
console.log(URL_query_parser('https://example.com?foo=1&bar=2'));
/*
//// URL Knowledge
let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));
params.append('foo', 4);
console.log(params.toString()); // "foo=1&bar=2&foo=4"
console.log(url.toString()); // "https://example.com/?foo=1&bar=2"
//Prints 'foo=1&bar=2&foo=4'
// note: params can also be directly created
url = new URL('https://example.com?foo=1&bar=2');
params = url.searchParams;
// or even simpler
params = new URLSearchParams('foo=1&bar=2');
*/
/*
// decode URI component
try {
var a = decodeURIComponent('%E0%A4%A');
} catch(e) {
console.error(e);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment