Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get top domain from string

Tags:

javascript

I want to get the top domain from strings such as:

domain.com -> domain.com
subdomain.domain.com -> domain.com
subdomain.domain.co.uk -> domain.co.uk

Have the following function so far:

function gdn(h) {
    return h.substring(h.lastIndexOf(".", h.lastIndexOf(".") - 1) + 1);
}

Problem is that this does not work with co.uk domains. The return for:

hello.domain.co.uk -> co.uk

Want it to be domain.co.uk

Any ideas?

like image 979
Alosyius Avatar asked May 06 '26 00:05

Alosyius


1 Answers

I don't think it's possible without checking for specific extensions like ".co.uk". At least it is not possible using just character-counting or by counting dots.

Also confirmed by this answer: How to get domain name only using javascript?

Regarding the answer mentioned above, note that the list of TLD's has grown alot since then, so make sure you update your list, if you want to use that answer as a base for your end solution. Fresh list: List of TLD's from IANA.org

like image 131
Gertsen Avatar answered May 08 '26 15:05

Gertsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!