function parseQuery(input) {
const search = input.includes('?') ? input.split('?')[1] : input;
return Object.fromEntries(new URLSearchParams(search));
}
function buildQuery(params) {
return new URLSearchParams(
Object.entries(params).filter(([, v]) => v !== null && v !== undefined)
).toString();
}
// Usage
console.log(parseQuery('?page=2&q=hello+world&sort=asc'));
// { page: '2', q: 'hello world', sort: 'asc' }
console.log(buildQuery({ page: 2, q: 'hello world', empty: null }));
// page=2&q=hello+world
Create a free account and build your private vault. Share publicly whenever you want.