Skip to content

Instantly share code, notes, and snippets.

@w3collective
Last active September 7, 2022 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/f68eec647f04a260a656cfbf9053dc86 to your computer and use it in GitHub Desktop.
Save w3collective/f68eec647f04a260a656cfbf9053dc86 to your computer and use it in GitHub Desktop.
Get the domain name from a URL in JavaScript
const url = "https://www.example.com/blog?search=hello&world";
let domain = (new URL(url));
domain = domain.hostname;
console.log(domain); //www.example.com
// OR strip the www
domain = domain.hostname.replace('www.','');
console.log(domain); //example.com
// Other properties
const pathname = domain.pathname;
console.log(pathname); // blog
const protocol = domain.protocol;
console.log(protocol); // https
const search = domain.search;
console.log(search); // ?search=hello&world
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment