In short
JavaScript window.location lets you read every part of the current page's URL and send the user to a new one. You will learn href, pathname, search and hash, read query strings with URLSearchParams, and build a "?page=2" filter. What are the parts of a URL in window.location?
JavaScript window.location lets you read every part of the current page's URL and send the user to a new one. You will learn href, pathname, search and hash, read query strings with URLSearchParams, and build a "?page=2" filter.
What are the parts of a URL in window.location?
A URL is the address of a page, like a postal address for the web. window.location (or just location) breaks it into handy pieces. Imagine the user is on this address:
https://shop.example.com:8080/products/shoes?color=red&page=2#reviews
Run this in the console of any page to see the pieces of that page's URL:
console.log(location.href); // the whole URL
console.log(location.protocol); // "https:"
console.log(location.host); // "shop.example.com:8080"
console.log(location.hostname); // "shop.example.com"
console.log(location.port); // "8080"
console.log(location.pathname); // "/products/shoes"
console.log(location.search); // "?color=red&page=2"
console.log(location.hash); // "#reviews"
console.log(location.origin); // "https://shop.example.com:8080"
For the example URL above, the comments show what you would get. Here is the same thing as a reference table:
| Property | Example value | Meaning |
|---|---|---|
href | full URL | The complete address |
protocol | "https:" | How the page is loaded (note the colon) |
host | "shop.example.com:8080" | Domain plus port |
hostname | "shop.example.com" | Domain only |
port | "8080" | Port number (empty string if default) |
pathname | "/products/shoes" | The path after the domain |
search | "?color=red&page=2" | The query string, including ? |
hash | "#reviews" | The fragment, including # |
origin | "https://shop.example.com:8080" | Protocol, host and port together |
Note: All of these are strings.
location.portis"8080", not the number8080, andsearchandhashkeep their?and#characters.
How to read query string parameters with URLSearchParams
The query string is the part after ?. It holds key-value pairs like color=red joined with &. Splitting it by hand is error-prone, so modern JavaScript gives you URLSearchParams:
// Pretend the page URL is ...?color=red&size=42&page=2
const params = new URLSearchParams("?color=red&size=42&page=2");
// In a real page you would write: new URLSearchParams(location.search)
console.log(params.get("color")); // Output: red
console.log(params.get("page")); // Output: 2 (a string!)
console.log(params.has("size")); // Output: true
console.log(params.get("brand")); // Output: null
const page = Number(params.get("page") ?? 1);
console.log(page + 1); // Output: 3
params.set("page", 3); // change a value
params.append("tag", "sale"); // add a new one
params.delete("size"); // remove one
console.log(params.toString()); // Output: color=red&page=3&tag=sale
get() returns the value as a string, or null if the key is missing. That is why we use ?? 1 for a default and Number() to turn "2" into 2. set, append and delete change the parameters, and toString() turns them back into a query string (without the ?). URLSearchParams also handles special characters for you: a space becomes + and & inside a value is encoded safely.
How to work with any URL using the URL object
location only describes the current page. To read or build any address, use the URL object. It has the same properties as location, plus a ready-made searchParams:
const link = new URL("https://shop.example.com/products?color=red#top");
console.log(link.hostname); // Output: shop.example.com
console.log(link.searchParams.get("color")); // Output: red
link.searchParams.set("page", 2);
link.hash = "";
console.log(link.href);
// Output: https://shop.example.com/products?color=red&page=2
// Relative URLs need a base:
const next = new URL("/cart", "https://shop.example.com/products");
console.log(next.href);
// Output: https://shop.example.com/cart
Changing searchParams updates the href automatically. The second argument to new URL() is a base address, so you can turn a relative path like /cart into a full URL. new URL(location.href) gives you an editable copy of the current page's URL.
Common mistake: Building URLs by gluing strings together, like
"/search?q=" + userText. If the user typesshoes & socks, the&breaks your query. UseURLSearchParamsorurl.searchParams.set(), which encode values correctly.
How to redirect with JavaScript: assign vs replace vs reload
You can send the user to another page in three main ways:
| Method | What it does | Back button? |
|---|---|---|
location.href = url | Goes to the new URL | Returns to this page |
location.assign(url) | Same as setting href | Returns to this page |
location.replace(url) | Goes to the new URL, replacing the current entry | Skips this page |
location.reload() | Loads the current page again | No new entry |
// Normal navigation, like clicking a link:
location.assign("https://example.com/");
// Redirect that removes the current page from history
// (good for an old address that has moved):
location.replace("https://example.com/new-page");
// Change only the hash: the page does NOT reload, it jumps to id="reviews"
location.hash = "reviews";
Use assign (or href) for normal moves. Use replace when the current page should not be visited again, for example after a "Redirecting..." screen, so the Back button does not trap the user in a loop. Changing only location.hash does not reload the page; it scrolls to the element with that id.
Tip: Changing
location.searchdoes reload the page. If you want to update the URL without reloading, usehistory.pushState, which you will learn in the next lesson.
Example: building a "?page=2" filter for a product list
Let's put it together. This page reads ?category= and ?page= from the URL, shows the right products, and builds "Next page" and category links:
<!DOCTYPE html>
<html lang="en">
<body>
<nav>
<a href="?category=all">All</a>
<a href="?category=shoes">Shoes</a>
<a href="?category=bags">Bags</a>
</nav>
<ul id="list"></ul>
<a id="next" href="#">Next page</a>
<script>
const products = [
{ name: "Runner", category: "shoes" }, { name: "Hiker", category: "shoes" },
{ name: "Sandal", category: "shoes" }, { name: "Tote", category: "bags" },
{ name: "Backpack", category: "bags" }, { name: "Clutch", category: "bags" }
];
const perPage = 2;
const params = new URLSearchParams(location.search);
const category = params.get("category") ?? "all";
const page = Math.max(1, Number(params.get("page")) || 1);
const filtered = products.filter(
(p) => category === "all" || p.category === category
);
const start = (page - 1) * perPage;
const visible = filtered.slice(start, start + perPage);
document.querySelector("#list").innerHTML = visible
.map((p) => `<li>${p.name}</li>`)
.join("") || "<li>No products here.</li>";
// Build the "next page" link, keeping the current category
const nextParams = new URLSearchParams({ category, page: page + 1 });
document.querySelector("#next").href = `?${nextParams}`;
</script>
</body>
</html>
Open the page and you see "Runner" and "Hiker". Click "Next page" and the URL becomes ?category=all&page=2, showing "Sandal" and "Tote". Click "Bags" and only bags appear. Number(params.get("page")) || 1 turns a missing or broken value into 1, and Math.max(1, ...) stops negative pages. Because the state lives in the URL, users can bookmark or share the exact page they are looking at.
Practice exercise
Make a search page with a text box and a "Search" button. When the button is clicked, go to ?q=<the text> using URLSearchParams (so spaces and & are encoded). When the page loads, read q from location.search, put it back into the text box and show "You searched for: ..." below it.
Hint: use location.search = new URLSearchParams({ q: input.value }).toString(); to navigate, and new URLSearchParams(location.search).get("q") ?? "" to read it.
Key takeaways
locationsplits the current URL intohref,protocol,host,pathname,search,hashand more; all are strings.URLSearchParamsreads and builds query strings safely withget,set,has,appendanddelete.- The
URLobject works with any address and has its ownsearchParams. assignkeeps the current page in history,replaceremoves it, andreloadloads the page again.- Keeping filters and page numbers in the URL makes them bookmarkable and shareable.