iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Location

window.location describes the page's URL and lets you navigate. The shape mirrors a parsed URL.

Parts

PropertyFor https://app.io:8080/path?x=1#top
hrefThe whole string. Writable — assigning navigates.
origin"https://app.io:8080"
protocol"https:"
host"app.io:8080"
hostname"app.io"
port"8080"
pathname"/path"
search"?x=1"
hash"#top"

Navigation methods

JS
location.assign("/profile");            // navigate, adds history entry
location.replace("/profile");           // navigate WITHOUT history entry
location.reload();                      // reload current page
location.reload(true);                  // (legacy) force reload from server

Read & modify query parameters

JS
// Modern way — URLSearchParams
const params = new URLSearchParams(location.search);
params.get("token");
params.set("page", 2);
location.search = params.toString();    // navigates with new query

// Full URL parsing
const url = new URL(location.href);
url.searchParams.set("ref", "header");
history.replaceState(null, "", url);    // update bar without reload
Tip: Use URL + URLSearchParams over manual string concat. They handle encoding, edge cases (no ?, repeated keys), and are easier to read.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Location!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Reload the current page.

location. ();

Test yourself

Q1. Reload the page without a server round-trip-history entry with…
Q2. Parse query parameters cleanly with…
Q3. Navigate without adding a history entry with…

Discussion

Loading…