2015-11-03 53 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); 
 
}