URL & History

Working with URLs

Example

The URL and URLSearchParams classes parse and build URLs safely:

const url = new URL("https://careeroza.com/jobs?city=Hyderabad&type=remote#top");
console.log(url.hostname, url.pathname, url.hash);
console.log(url.searchParams.get("city"));
url.searchParams.set("page", "2");
url.searchParams.delete("type");
console.log(url.toString());

Output

careeroza.com /jobs #top
Hyderabad
https://careeroza.com/jobs?city=Hyderabad&page=2#top

The History API

Single-page apps change the URL without reloading the page:

history.pushState({ page: 2 }, "", "/jobs?page=2");   // new history entry
history.replaceState(null, "", "/jobs?page=3");       // replace current entry
window.addEventListener("popstate", (e) => {
  console.log("Back/forward pressed, state:", e.state);
});