Get the Current URL with JavaScript

Web Design & Web Development

In this article, I will introduce how to get the current URL with JavaScript.

Window Location

To get the current URL, you can use the JavaScript window.location object.

Let's take a look at an example of the current page address (URL) that contains several components - the protocol, domain, port, path, query and hash:

https://www.plantpot.works:8080/example/index.html?s=JavaScript#toc2

Get the full URL path

To get the full URL path of the current URL, you can use the window.location.href property:

const url = window.location.href;

console.log(url);
// https://www.plantpot.works:8080/example/index.html?s=JavaScript#toc2
Sponsored links

Get the URL components

To get the components of the current URL, you can use each property of the window.location object:

// Protocol
const protocol = window.location.protocol;

console.log(protocol);
// https://


// host
const host = window.location.host;

console.log(host);
// www.plantpot.works:8080


// hostname
const hostname = window.location.hostname;

console.log(hostname);
// www.plantpot.works


// port
const port = window.location.port;

console.log(port);
// 8080


// pathname
const path = window.location.pathname;

console.log(path);
// /example/index.html


// query
const query = window.location.search;

console.log(path);
// ?s=JavaScript


// hash
const hash = window.location.hash;

console.log(hash);
// #toc2