【问题标题】:How to extract the TLD from the URL in JavaScript如何从 JavaScript 中的 URL 中提取 TLD
【发布时间】:2018-01-02 11:35:02
【问题描述】:

我想从 URL 中提取 TLD,但它给了我整个 URL。 例如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!")
    }

【问题讨论】:

标签: javascript google-chrome-extension


【解决方案1】:

要获取域的最后一部分,例如 example.com 中的 com,请使用以下内容:

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

但是,像 co.uk 这样的 eTLD 需要特殊情况。如果你想硬编码检查.co.uk:

const isUK = window.location.origin.endsWith('.co.uk');

【讨论】:

    【解决方案2】:

    您可以为此使用URL 类:

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

    此外,生成的 url 对象具有更多有用的属性,并使浏览器执行字符串解析部分,因此在大多数情况下您不必摆弄正则表达式。

    要提取 TLD 主机名,您可以使用以下内容:

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

    docs

    【讨论】:

    • RegExp 不捕获任何内容(没有括号),如果可以,它只会提取最后一部分(即.uk,而不是.com.uk)
    • 我添加了一些括号来让它捕捉到一些东西……
    • 您是否尝试过针对 www.google.com.uk 测试 RegExp(或您提到的其他方式)?
    猜你喜欢
    • 2010-11-07
    • 2012-11-10
    • 2019-03-23
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多