๐Ÿ”— JavaScript

The URL API โ€” Parse Query Params Without Regex

๐Ÿ“… Jul 4, 2026 โฑ 3 min read

Splitting URLs with string hacks is a bug factory. The URL API parses, builds and updates them correctly โ€” and unlocks shareable app state.

Reading

// current page: /dsa/practice?p=two-sum&lang=js
const params = new URLSearchParams(location.search);
params.get("p");         // "two-sum"
params.get("missing");   // null
params.has("lang");      // true

const u = new URL("https://site.com:8080/path?x=1#top");
u.hostname; u.pathname; u.hash; u.searchParams.get("x");

Building โ€” encoding handled for you

const url = new URL("https://api.site.com/search");
url.searchParams.set("q", "anna university");   // spaces auto-encoded
url.searchParams.set("page", 2);
fetch(url);   // https://api.site.com/search?q=anna+university&page=2

The power move: state in the URL

function setFilter(category) {
  const params = new URLSearchParams(location.search);
  params.set("cat", category);
  history.replaceState(null, "", "?" + params);   // update URL, NO reload
}

// on load, restore:
const saved = new URLSearchParams(location.search).get("cat");
if (saved) applyFilter(saved);

Now filters survive refresh and are shareable โ€” paste the link, get the same view. Our DSA judge does exactly this with ?p=problem-slug.

โ† All Articles