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
> 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
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
let domain = (new URL(url));
domain = domain.hostname;
console.log(domain); //www.example.com
xxxxxxxxxx
/**
* Extracts only the website name from a url
* @example "Twitter" from "https://twitter.com/example"
* @param {string} url the link to extract the name from
* @returns Website name
*/
function extractWebsiteName(url) {
if (url) {
const regex = /(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:([^./]+)\.)?([^./]+\.com)/;
const matches = url.match(regex);
const [, subdomain, domain] = matches;
let socialMediaName = subdomain
? subdomain.charAt(0).toUpperCase() + subdomain.slice(1)
: domain.charAt(0).toUpperCase() + domain.slice(1);
socialMediaName = socialMediaName.replace(/\.[^/.]+$/, '');
return socialMediaName; // Remove the top-level domain
} else {
return '';
}
}
console.log(extractWebsiteName("https://www.mydomain.com/blog?search=hello&world")); // Mydomain