As @edelwater 's answer says, strict way is too difficult.
Following is short code that works only for simple cases, which url starts with "https://" and top level domain is one(e.g. ".com", not "co.uk") and domain ends with '/'(e.g. "https://images.google.com/blash", not "https://images.google.com".
const PROTOCOL_LENGTH = "https://".length; // =8
const url = "https://images.google.com/blash"
const subdomain = url.substring(PROTOCOL_LENGTH , url.indexOf('/', PROTOCOL_LENGTH +1)).split('.').reverse()[1];
Following is function form and test cases:
const PROTOCOL_LENGTH = "https://".length; // =8
const extract_subdomain = (url) =>{
return url.substring(PROTOCOL_LENGTH, url.indexOf('/', PROTOCOL_LENGTH + 1)).split('.').reverse()[1];
}
console.log(extract_subdomain("https://www.google.com/blah"));// => google
console.log(extract_subdomain("https://www.images.google.com/"));// => google
////Following is failed cases
//domain doesn't end with '/'
console.log(extract_subdomain("https://images.google.com"));// => undefined
//top level domain("co.uk") is not one
console.log(extract_subdomain("https://www.google.co.uk/blah"));// => co
If you want a strict library, following may be help(note: I didn't check this): remusao/tldts: JavaScript Library to extract domains, subdomains and public suffixes from complex URIs.