Get second level domain name from URL

sublime picture sublime · Sep 19, 2014 · Viewed 11k times · Source

Is there a way to get top level domain name from the url

for e.g., "https://images.google.com/blah" => "google"

I found this:

var domain = new URL(pageUrl).hostname; 

but it gives me "images.google.com" instead of just google.

Unit tests I have are:

https://images.google.com   => google
https://www.google.com/blah => google
https://www.google.co.uk/blah => google
https://www.images.google.com/blah => google

Answer

Rob M. picture Rob M. · Sep 19, 2014

You could do this:

location.hostname.split('.').pop()

EDIT

Saw the change to your question, you would need a list of all TLDs to match against and remove from the hostname, then you could use split('.').pop()

// small example list
var re = new RegExp('\.+(co.uk|me|com|us)')
var secondLevelDomain = 'https://www.google.co.uk'.replace(re, '').split('.').pop()