Last active
September 7, 2022 07:47
-
-
Save w3collective/f68eec647f04a260a656cfbf9053dc86 to your computer and use it in GitHub Desktop.
Get the domain name from a URL in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/get-domain-name-url-javascript/