Skip to content

Instantly share code, notes, and snippets.

@w3collective
Last active Feb 3, 2021
Embed
What would you like to do?
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(protocol); // ?search=hello&world
@w3collective

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented Dec 23, 2020

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