Q13: Write a URL Query String Parser and Builder
Implement helper functions to convert URL query parameters into an object map and convert an object map back into an encoded URL query string.
Query Parser and Stringifier
function parseQuery(str) {
if (!str) return {};
const queryString = str.startsWith('?') ? str.slice(1) : str;
return queryString.split('&').reduce((acc, param) => {
const [key, value] = param.split('=');
if (key) acc[decodeURIComponent(key)] = decodeURIComponent(value || '');
return acc;
}, {});
}
function stringifyQuery(obj) {
return Object.entries(obj)
.map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
.join('&');
}
console.log(parseQuery('?name=Alex&age=25')); // { name: 'Alex', age: '25' }
console.log(stringifyQuery({ a: '1', b: '2' })); // 'a=1&b=2'💡 Splitting by delimiters extracts key-value pairs while URI encoding functions prevent character corruption.
Key Takeaways
- Processes delimiter split strings using split('&') and split('=').
- Encodes and decodes special URI characters using encodeURIComponent and decodeURIComponent.
Knowledge Check
Why must encodeURIComponent be used when stringifying query parameters?