JavaScript Snippets
Updated Jan 13, 2025
Getting the hostname
from a URL
I found this helpful as a solution for formatting a URL (for example, to display it cleanly on a page).
const url = "https://developer.mozilla.org/en-US/docs/Web/API/URL"
const formatURL = (url) => {
// Create URL object
const urlObject = new URL(url);
// Return hostname property value
return urlObject.hostname;
}
console.log("Hostname:", formatURL(url)) // developer.mozilla.org