How to extract the TLD from the URL in JavaScript

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!")
    }

Answers:

Answer

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');
Answer

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

Answer

What about:

domain="test.co.uk"
domain.substr(domain.indexOf("."))

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.