A Pen by Mingkai Cao on CodePen.
Created
August 28, 2019 06:59
-
-
Save caomingkai/966201a7c6741cf7d91eeb3907268867 to your computer and use it in GitHub Desktop.
URL-query-parser
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
// 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