Write a function parseQuery(url) that extracts query parameters from a URL string and returns them as a plain object with key-value pairs. Decoded values should handle basic encoded characters like %20 or +, and duplicate keys can just overwrite earlier ones.
function parseQuery(url) {
// your code here
}
Rules:
Return a plain object of key-value string pairs
Return an empty object if the URL contains no query string
Use built-in web standard APIs like URLSearchParams or URL, or parse manually
Post your solution as a reply. Answer goes up in about a day.
Challenge solution: The original problem statement implies a function that takes a URL string and returns an object of its query parameters.
One way to do it:
function parseQuery(url) {
const urlObj = new URL(url);
const params = {};
for (const [key, value] of urlObj.searchParams.entries()) {
params[key] = value;
}
return params;
}
Why:
This solution leverages the built-in URL and URLSearchParams web APIs, which are designed for this exact purpose. The URL constructor parses the input string, and its searchParams property provides an iterator over all key-value pairs, automatically handling decoding and duplicate keys by overwriting them as specified. This approach is robust and idiomatic for JavaScript in a browser or Node.js environment.
The URLSearchParams approach is definitely the right move for standard cases. I’ve seen too many custom parsers fail on some obscure encoding or a stray equals sign.
But I do wonder about the behavior with non-standard inputs. What happens if you get a query string like ?key1=val1&&key2=val2 or ?key1==val1? Sometimes APIs return those in weird formats that URLSearchParams might flatten unexpectedly.
I’m still leaning into URLSearchParams for most things.
It’s just too convenient. But if we’re talking about specific weird inputs, I’ve got to throw out the one where a key or value has an actual & in it, but it’s not encoded. Like ? name=Waffle&Fries. URLSearchParams will split that into two separate entries, name: Waffle and Fries: null. If you actually need name: Waffle&Fries, then you’re probably going to have to do a pre-parse regex or something before it even hits the URL object.
Hmm, URLSearchParams is great for standard cases but that unencoded ampersand is a classic. I usually handle that by doing a quick string replace on the raw search string before passing it to the constructor.
Replacing & with a placeholder works if you know the specific key structure.