How to get the current URL with JavaScript

How to get the current URL with JavaScript

There is a property inside the ​location ​object which will give you the full URL of the page you are currently browsing.

window​.​location​.​href; // e.g. https://hashnode.com

In addition, you can pass the string that’s contained in the ​href ​property to construct a new ​URL ​object.

const url = new​ ​URL​(​window​.​location​.​href​);

{
  hash: "",
  host: "hashnode.com",
  hostname: "hashnode.com",
  href: "https://hashnode.com/somepage",
  origin: "https://hashnode.com",
  password: "",
  pathname: "/somepage",
  port: "",
  protocol: "https:",
  search: "",
  searchParams: URLSearchParams {}
}

This will give you access to properties like the ​hostname, path, origin etc which makes it easier to extract parts of the URL that you may need.

Follow me on Twitter for more tutorials 👍