2015-11-03 52 views
-1

有没有懒惰的方式来获得“顶级”主机的变量,而不诉诸if()?Javascript返回只是主域名

  • 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,
+1

您可以尝试[正则表达式](http://eloquentjavascript.net/09_regexp.html)或[String.prototype.split](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split) – nils

+2

'cabbages.example.co.uk'怎么样?这样做需要知道每个顶级域名的命名约定。 – Barmar

回答

1

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

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

的方式来写一个正则表达式充足,但一个是

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

太好了,非常感谢。与拆分拼接并加入 –

0

您可以使用正则表达式来得到你想要的字符串的一部分:

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); 
 
}