HTML Location pathname
Property: A Comprehensive Guide
The HTML Location
pathname
property returns the path component of the current URL. This property is part of the Location
object, which provides information about the current URL and methods to manipulate it. Understanding and utilizing the pathname
property is crucial for web developers who need to work with URL structures and route users within a web application.
What is the Location pathname
Property?
The pathname
property of the Location
object represents the part of the URL that follows the domain name and precedes any query parameters (?
) or hash (#
). It essentially defines the specific resource or page being accessed on the server.
Purpose of the Location pathname
Property
The primary purposes of the pathname
property include:
- Accessing the Path: Retrieving the path segment of the current URL.
- URL Routing: Using the path to determine which content to display or which action to perform.
- Navigation: Modifying the path to navigate to different sections of a website.
- Analytics: Tracking which pages users are visiting within a web application.
Syntax
The syntax for accessing the pathname
property is straightforward:
let path = window.location.pathname;
Here, path
will be a string containing the path component of the current URL.
Key Characteristics
- Read-Only: The
pathname
property is read-only. You can retrieve its value, but you cannot directly modify the current URL’s path by assigning a new value towindow.location.pathname
. - String Value: It returns a string representing the path, including leading slashes but excluding the domain, query parameters, and hash.
- URL Encoding: The returned path is URL-encoded, meaning special characters are represented using percent encoding (e.g., spaces are encoded as
%20
).
Examples
Let’s explore practical examples of using the pathname
property to extract and utilize the path component of a URL.
Basic Example: Displaying the Pathname
This example demonstrates how to retrieve the current URL’s pathname
and display it on a webpage.
<!DOCTYPE html>
<html>
<head>
<title>Location Pathname Example</title>
</head>
<body>
<h1>Location Pathname Example</h1>
<p id="pathnameDisplay"></p>
<script>
const pathnameDisplay_basic = document.getElementById("pathnameDisplay");
const currentPath_basic = window.location.pathname;
pathnameDisplay_basic.textContent = "Current Pathname: " + currentPath_basic;
</script>
</body>
</html>
Output:
If the current URL is https://www.example.com/about/us?param=value#section
, the output will be:
Current Pathname: /about/us
Using Pathname for Simple Routing
This example shows how to use the pathname
to simulate simple client-side routing, displaying different content based on the path.
<!DOCTYPE html>
<html>
<head>
<title>Simple Routing Example</title>
</head>
<body>
<h1>Simple Routing Example</h1>
<div id="contentArea"></div>
<script>
const contentArea_routing = document.getElementById("contentArea");
const currentPath_routing = window.location.pathname;
switch (currentPath_routing) {
case "/":
contentArea_routing.textContent = "Welcome to the Home Page!";
break;
case "/about":
contentArea_routing.textContent = "Learn more About Us.";
break;
case "/contact":
contentArea_routing.textContent = "Contact us for inquiries.";
break;
default:
contentArea_routing.textContent = "404 - Page Not Found.";
}
</script>
</body>
</html>
Output:
- If the URL is
https://www.example.com/
, the output will be:
Welcome to the Home Page!
- If the URL is
https://www.example.com/about
, the output will be:
Learn more About Us.
- If the URL is
https://www.example.com/nonexistent
, the output will be:
404 - Page Not Found.
Extracting Path Segments
This example demonstrates how to split the pathname
into segments, allowing you to work with individual parts of the path.
<!DOCTYPE html>
<html>
<head>
<title>Extracting Path Segments</title>
</head>
<body>
<h1>Extracting Path Segments</h1>
<p id="pathSegments"></p>
<script>
const pathSegmentsDisplay = document.getElementById("pathSegments");
const currentPath_segments = window.location.pathname;
const segments_segments = currentPath_segments.split("/");
const validSegments_segments = segments_segments.filter(segment => segment !== "");
pathSegmentsDisplay.textContent = "Path Segments: " + validSegments_segments.join(", ");
</script>
</body>
</html>
Output:
If the current URL is https://www.example.com/blog/articles/example-post
, the output will be:
Path Segments: blog, articles, example-post
Modifying the Location using window.location.assign()
While you cannot directly modify window.location.pathname
, you can use methods like window.location.assign()
to navigate to a new URL with a modified path.
<!DOCTYPE html>
<html>
<head>
<title>Modifying Pathname via Assign</title>
</head>
<body>
<h1>Modifying Pathname via Assign</h1>
<button id="navigateButton">Go to About Page</button>
<script>
const navigateButton_assign = document.getElementById("navigateButton");
navigateButton_assign.addEventListener("click", function() {
const newPath_assign = "/about";
window.location.assign(newPath_assign);
});
</script>
</body>
</html>
Explanation:
Clicking the “Go to About Page” button will navigate the browser to the /about
path on the same domain.
Constructing URLs Dynamically
This example shows how to construct URLs dynamically based on user input or other variables, and then navigate to the new URL.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic URL Construction</title>
</head>
<body>
<h1>Dynamic URL Construction</h1>
<input type="text" id="articleId" placeholder="Enter Article ID">
<button id="viewArticle">View Article</button>
<script>
const articleIdInput = document.getElementById("articleId");
const viewArticleButton = document.getElementById("viewArticle");
viewArticleButton.addEventListener("click", function() {
const articleId_construct = articleIdInput.value;
const newPath_construct = "/articles/" + articleId_construct;
window.location.assign(newPath_construct);
});
</script>
</body>
</html>
Explanation:
Entering an article ID (e.g., “123”) and clicking the “View Article” button will navigate the browser to /articles/123
on the same domain.
Use Case Example: Implementing a Breadcrumb Navigation
Let’s create a practical example demonstrating how to use the pathname
property to dynamically generate a breadcrumb navigation.
<!DOCTYPE html>
<html>
<head>
<title>Breadcrumb Navigation</title>
<style>
.breadcrumb {
list-style: none;
display: flex;
padding: 0;
}
.breadcrumb li {
margin-right: 5px;
}
.breadcrumb li:not(:last-child)::after {
content: ">";
margin-left: 5px;
}
.breadcrumb a {
text-decoration: none;
color: blue;
}
</style>
</head>
<body>
<h1>Breadcrumb Navigation</h1>
<ul class="breadcrumb" id="breadcrumbNav">
</ul>
<script>
const breadcrumbNav = document.getElementById("breadcrumbNav");
const currentPath_breadcrumb = window.location.pathname;
const segments_breadcrumb = currentPath_breadcrumb.split("/").filter(segment => segment !== "");
let currentUrl = "";
segments_breadcrumb.forEach(segment => {
currentUrl += "/" + segment;
const listItem = document.createElement("li");
const link = document.createElement("a");
link.href = currentUrl;
link.textContent = segment;
listItem.appendChild(link);
breadcrumbNav.appendChild(listItem);
});
</script>
</body>
</html>
Explanation:
This example generates a breadcrumb navigation based on the current URL’s pathname
. It splits the path into segments and creates a list of links, each pointing to a deeper level in the site hierarchy. For example, if the URL is https://www.example.com/blog/articles/example-post
, the breadcrumb navigation will be:
blog > articles > example-post
Browser Support
The pathname
property is supported by all major browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
Conclusion
The Location
pathname
property is a fundamental tool for web developers, enabling you to access and utilize the path component of a URL. Whether for simple routing, extracting path segments, or constructing dynamic URLs, understanding and using the pathname
property is essential for building modern web applications. By combining it with other Location
object properties and methods, you can create powerful navigation and content management solutions.