location: Reading URLs, Query Params, and RedirectsThe JavaScript window.location object exposes the current page URL and lets you inspect its parts, parse query strings, or redirect the browser. Pairing window.location with URL and URLSearchParams replaces fragile regex string splitting.
window.locationFor a URL like https://kodersolution.com:443/tutorials/javascript?page=2#faq:
location.origin: "https://kodersolution.com:443" (scheme + host + port)location.pathname: "/tutorials/javascript"location.search: "?page=2" (query string)location.hash: "#faq" (fragment identifier)Use new URLSearchParams(location.search) to read query parameters cleanly, and choose between location.assign(url) (keeps Back button history) and location.replace(url) (replaces current history entry).
console.log("Current href:", window.location.href);
console.log("Pathname:", window.location.pathname);
// Parse query parameters reliably using URL and URLSearchParams
const sampleUrl = new URL("https://kodersolution.com/search?q=async+await&page=2");
const params = sampleUrl.searchParams;
console.log("Search term:", params.get("q")); // "async await"
console.log("Page number:", params.get("page")); // "2"
// Build safe redirect URLs without string-concatenation bugs
params.set("page", "3");
console.log("Next URL:", sampleUrl.toString());
?next= query parameters: Passing user-supplied URLs straight to location.href = nextUrl creates Open Redirect phishing vulnerabilities. Validate that relative paths start with / and are not //evil.com.location.search manually with .split("&"): Manual splitting breaks on + spaces and %20 URL encoding. Always use URLSearchParams.location.reload(true) expecting cache bypass: Modern browsers ignore the deprecated boolean parameter on location.reload().location.assign() and location.replace()?location.assign(url) (or setting location.href = url) navigates while keeping the current page in browser Back history. location.replace(url) overwrites the current history entry so pressing Back skips the old page—useful after login redirects.
Build the updated URL with new URL(window.location.href) and update the browser URL field silently using history.replaceState(null, "", url).
location.hash reload the page?No, changing #section scrolls to that matching element ID (if present) and fires a "hashchange" event without making a new server request.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.