JavaScript

Parse URL Query String

by @admin
10h ago
Apr 28, 2026
Public
Parses a URL query string into a plain key-value object. Uses the built-in URLSearchParams API — no regex required. Handles duplicate keys (returns the first value), percent-encoded characters, and works with both full URLs and raw query strings. Pairs nicely with buildQueryString.
JavaScript
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
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.