JavaScript location.href

location.href returns the complete URL of the current page. Assigning a new URL to it also navigates the browser.

const currentUrl = location.href;
console.log(currentUrl);

Current value:

Get the directory path Top ↑

The original tutorial extracted the path using slice() and lastIndexOf(). That technique is retained below.

const path = location.href;
const index = path.lastIndexOf('/');
const rootPath = path.slice(0, index);
console.log(rootPath);

Directory path for this page:

A URL-object alternative Top ↑

For structured URL work, URL is usually clearer because it exposes origin, pathname, and query parameters separately.

const url = new URL(location.href);
const directory = url.origin + url.pathname.slice(0, url.pathname.lastIndexOf('/'));

JavaScript location Getting hostname Refresh the page




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer