How to get the domain name without subdomains?
e.g. if the url is "http://one.two.roothost.co.uk/page.html" how to get "roothost.co.uk"?
let domain = (new URL(url)); With the object created there are a number of properties we can access. We're interested in the hostname property which returns a string containing the domain name. If you require a naked domain (without the www) it can be removed using the replace() method.
Following is a solution to extract a domain name without any subdomains. This solution doesn't make any assumptions about the URL format, so it should work for any URL. Since some domain names have one suffix (.com
), and some have two or more (.co.uk
), to get an accurate result in all cases, we need to parse the hostname using the Public Suffix List, which contains a list of all public domain name suffixes.
First, include the public suffix list js api in a script tag in your HTML, then in JavaScript to get the hostname you can call:
var parsed = psl.parse('one.two.roothost.co.uk'); console.log(parsed.domain);
...which will return "roothost.co.uk". To get the name from the current page, you can use location.hostname
instead of a static string:
var parsed = psl.parse(location.hostname); console.log(parsed.domain);
Finally, if you need to parse a domain name directly out of a full URL string, you can use the following:
var url = "http://one.two.roothost.co.uk/page.html"; url = url.split("/")[2]; // Get the hostname var parsed = psl.parse(url); // Parse the domain document.getElementById("output").textContent = parsed.domain;
JSFiddle Example (it includes the entire minified library in the jsFiddle, so scroll down!): https://jsfiddle.net/6aqdbL71/2/
You can use parse-domain
to do the heavy lifting for you. This package considers the public suffix list
and returns an easy to work with object breaking up the domain.
Here is an example from their readme:
npm install parse-domain
import { parseDomain, ParseResultType } from 'parse-domain'; const parseResult = parseDomain( // should be a string with basic latin characters only. more details in the readme 'www.some.example.co.uk', ); // check if the domain is listed in the public suffix list if (parseResult.type === ParseResultType.Listed) { const { subDomains, domain, topLevelDomains } = parseResult; console.log(subDomains); // ["www", "some"] console.log(domain); // "example" console.log(topLevelDomains); // ["co", "uk"] } else { // more about other parseResult types in the readme }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With