2

I want to extract the TLD from the URL but it's giving me the whole URL instead. For example https://www.google.com.uk -> .com.uk.

$(document).on("click", "a", function() {
       var href = $(this).attr("href");
       alert(href)// It gives me the whole link of website
    if(href.search(".com.uk")){
        alert("This website is AUTHENTIC!");
    }
    else
    {
        alert("Not AUTHENTIC!")
    }
isherwood
  • 58,414
  • 16
  • 114
  • 157
Mrkrabs
  • 41
  • 1
  • 5
  • `.co.uk` is not a TLD, it's a second-level domain. It is at best a [eTLD](https://en.wikipedia.org/wiki/Public_Suffix_List) which requires custom cases. – Bergi Jan 02 '18 at 13:29
  • Does this answer your question? [How to get domain name only using javascript?](https://stackoverflow.com/questions/8253136/how-to-get-domain-name-only-using-javascript) – kevlened Oct 08 '21 at 04:29

2 Answers2

9

To get the last piece of a domain, such as com in example.com, use something like:

const tld = window.location.origin.split('.').pop();

However, eTLDs like co.uk need special cases. If you want to hardcode a check for .co.uk:

const isUK = window.location.origin.endsWith('.co.uk');
OverCoder
  • 1,472
  • 23
  • 33
2

You can use the URL class for that:

var url = new URL(href);
console.log(url.pathname); // /some/path

Additionally the resulting url object has more useful properties and makes the browser do the string parsing part, so you do not have have to fiddle around with regular expressions in most cases.

To extract the TLD hostname you can use something like that:

url.hostname.split(/\./).slice(-2).join('.');

docs

philipp
  • 15,947
  • 15
  • 61
  • 106