【问题标题】:Regex to get SLD + TLD from domain string正则表达式从域字符串中获取 SLD + TLD
【发布时间】:2015-07-28 20:52:47
【问题描述】:

我有一个将域名作为参数的函数,但域必须采用xxx.com 的格式。例如http://subdomain.example.com 必须作为 example.com 传递给函数。

我已经编写了以下正则表达式,但它只返回 TLD (.com)。我是一个正则表达式的新手,所以真的看不出我哪里出错了......第一个语句是从domain 中提取http://,第二个语句应该提取任何子域。

var domain = req.query.domain.replace(/.*?:\/\//g, '').replace(/^[^.]+\./g, '');

使用上述正则表达式,http://example.com 变为 com。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    我认为直接匹配模式比匹配并删除它的补码更容易。我会使用模式/[^./]+\.[^./]+$/。这匹配在字符串末尾用句点分隔的两个非特殊字符运行。

    alert('http://subdomain.example.com'.match(/[^./]+\.[^./]+$/)[0]);
    alert('http://example.com'.match(/[^./]+\.[^./]+$/)[0]);

    【讨论】:

      【解决方案2】:

      一个更简单的答案是使用document.createElement 显示的技巧here

      要获取主机名和 TLD,您只需编写

      var link = document.createElement('a');
      link.href = req.query.domain;
      
      var formattedDomain = link.hostname; //yay
      

      【讨论】:

      • 这是节点,因此document 不可用。
      • 包含这些信息会很有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2014-04-09
      • 2014-10-08
      • 1970-01-01
      • 2011-06-15
      • 2016-04-05
      相关资源
      最近更新 更多