xxxxxxxxxx
function getDomainFromURL(url) {
const parsedURL = new URL(url);
return parsedURL.hostname;
}
const url = 'https://www.example.com/path?page=1';
const domain = getDomainFromURL(url);
console.log(domain);
xxxxxxxxxx
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
xxxxxxxxxx
var url = window.location.href;
var domain = url.replace('http://','').replace('https://','').split(/[/?#]/)[0];
xxxxxxxxxx
const url = 'https://www.mydomain.com/blog?search=hello&world';
const domain = (new URL(url)).hostname.replace('www.','');
xxxxxxxxxx
> Site:
https://www.google.com/search?q=js+get+domain
> window.location.hostname
'www.google.com'
> window.location.hostname.replace("www.","")
'google.com'
xxxxxxxxxx
let domain = (new URL(url));
domain = domain.hostname;
console.log(domain); //www.example.com
domain = domain.hostname.replace('www.','');
console.log(domain); //example.com
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
xxxxxxxxxx
url = http://localhost:4200/landing?query=1#2
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
xxxxxxxxxx
const url = 'http://www.youtube.com/watch?v=ClkQA2Lb_iE';
const { hostname } = new URL(url);
console.assert(hostname === 'www.youtube.com'); // true
xxxxxxxxxx
let domain = (new URL(url));
domain = domain.hostname;
console.log(domain); //www.example.com