How to get ONLY the name of an domain from an url
+--------------------------------------------+------------+
| input | output |
+--------------------------------------------+------------+
| http://google.com/abc.html | google |
| http://www.yahoo.com?abc | yahoo |
| https://youtube.co.in/abc/xyz.html | youtube |
| https://www.twitter.au.uk/abc&xyz.php | twitter |
+--------------------------------------------+------------+
This "output" will be used to create the name of an image "google.png"
On my angular app I have split the code in 3 parts:
Part 1
export function extractHostname(url: string): string {
let hostname;
// remove protocol
if (url.indexOf('//') > -1) {
hostname = url.split('/')[2];
} else {
hostname = url.split('/')[0];
}
// remove port
hostname = hostname.split(':')[0];
// remove query
hostname = hostname.split('?')[0];
return hostname;
}
Part 2 (here is my problem)
import { extractHostname } from './extractHostname';
export function extractRootDomain(url: string): string {
let domain = extractHostname(url);
const splitArr = domain.split('.');
const arrLen = splitArr.length;
// get root domain
if (arrLen > 2) {
domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
// see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
if (splitArr[arrLen - 2].length === 2 && splitArr[arrLen - 1].length === 2) {
domain = splitArr[arrLen - 3] + '.' + domain;
}
}
return domain;
}
Part 3 - Final step (return +domain+ to create image name)
import {extractRootDomain} from './extractRootDomain';
export function getFaviconFromUrl(url: string) {
const domain = extractRootDomain(url);
return 'https://mywebsite.com/img/'+domain+'.png;
}
Of corse, this work, but the return is google.com - and - I need just google
Someone can rewrite the code and paste here?