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:
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:
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.