Parse "?q=java%20script&page=2&tag=js&tag=css&debug" into an object (decode values, repeated keys become arrays, keys without values become true), then compare with URLSearchParams.
Solution
main.js
function parseQuery(qs) {
const result = {};
for (const part of qs.replace(/^\?/, "").split("&").filter(Boolean)) {
const [rawKey, rawValue] = part.split("=");
const key = decodeURIComponent(rawKey);
const value = rawValue === undefined ? true : decodeURIComponent(rawValue.replace(/\+/g, " "));
if (key in result) result[key] = [].concat(result[key], value);
else result[key] = value;
}
return result;
}
const qs = "?q=java%20script&page=2&tag=js&tag=css&debug";
console.log(parseQuery(qs));
const params = new URLSearchParams(qs);
console.log(params.get("q"), params.getAll("tag"), params.has("debug"));
Each key=value pair is split once; decodeURIComponent turns %20 back into a space. [].concat(existing, value) turns a repeated key into an array. In real code the built-in URLSearchParams does all of this.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!