【问题标题】:Javascript return just primary domain name [duplicate]Javascript仅返回主域名[重复]
【发布时间】:2015-11-03 16:51:01
【问题描述】:

有没有一种懒惰的方法来获取“顶级”主机的变量而不诉诸 if()?

  • example.com:返回 example.com,
  • cabbages.example.com:返回 example.com,
  • carrots.example.com:返回 example.com,
  • otherexample.com:返回 otherexample.com,
  • cabbages.otherexample.com:返回 otherexample.com,
  • carots.otherexample.com:返回 otherexample.com,

【问题讨论】:

标签: javascript


【解决方案1】:

对于您提供的测试用例,一种方法是使用拆分、拼接和连接。

window.location.hostname.split(".").splice(-2,2).join(".")

编写正则表达式的方法很多,但其中一种是

window.location.hostname.match(/[^\.]+\.[^\.]+$/)

【讨论】:

  • 太好了,非常感谢。使用拆分拼接并加入
  • www.google.com.au 怎么样,应该是 google.com.au,而不是 com.au
【解决方案2】:

您可以使用正则表达式来获取您想要的字符串部分:

url = url.replace(/^.*?([^\.]+\.[^\.]+)$/, '$1');

演示:

var urls = [
  'example.com',
  'cabbages.example.com',
  'carrots.example.com',
  'otherexample.com',
  'cabbages.otherexample.com',
  'carots.otherexample.com'
];

for (var i = 0; i < urls.length; i++) {
  var url = urls[i].replace(/^.*?([^\.]+\.[^\.]+)$/, '$1');
  console.log(url);
}

【讨论】:

    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多