Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active October 18, 2018 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsuby/fe0277c6b93f051651c6fb7e40120966 to your computer and use it in GitHub Desktop.
Save matsuby/fe0277c6b93f051651c6fb7e40120966 to your computer and use it in GitHub Desktop.
JavaScript one-liner function: parseQuery and buildQuery (>=ES2017)
// for ES2017
{
// "name=matsuby&age=27" => {name: "matsuby", age: "27"}
const parseQuery = qs => typeof qs!=="string"?{}:Object.assign({},...Object.entries([...new URLSearchParams(qs)].reduce((a,c)=>Object.assign(a,{[c[0]]:a[c[0]]?[...a[c[0]],c[1]]:[c[1]]}),{})).map(e=>({[e[0]]:e[1].join(",")})));
// {name: "matsuby", age: "27"} => "name=matsuby&age=27"
const buildQuery = qo => new URLSearchParams(Object.entries(qo).map(kv=>kv[1].split(",").map(v=>[kv[0],v])).reduce((a,c)=>a.concat(c),[])).toString();
const testParams = [
// expect:
// parse: query object
// build: query string
"name=matsuby&age=27", // standard
"?name=matsuby&age=27", // ignore first "?"
"name=matsuby&age=27&", // ignore last "&"
"?name=matsuby&age=27&", // ignore first "?" and ignore last "&"
"name=matsuby&name=john", // not unique => concat value string with ","(csv string)
"name=", // key only, value is empty string("")
"name", // key only, value is empty string("")
"?%E3%81%82=%E3%81%84", // decode uri
location.search, // browsing page test
// expect:
// parse: empty object({})
// build: empty string("")
"", 0, 1, true, false, null, undefined, NaN, [], {},
];
for (p of testParams) {
const t = p !== p ? p : JSON.stringify(p);
const pq = JSON.stringify(parseQuery(p));
const bq = JSON.stringify(buildQuery(parseQuery(p)));
console.log(`${t}: ${pq} => ${bq}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment