Javascript只返回主域名

时间:2015-11-03 16:51:01

标签: javascript

是否有一种懒惰的方法来获取"顶级"主持人没有求助于if()?

  • example.com:return example.com,
  • cabbages.example.com:return example.com,
  • carrots.example.com:return example.com,
  • otherexample.com:return otherexample.com,
  • cabbages.otherexample.com:return otherexample.com,
  • carots.otherexample.com:return otherexample.com,

2 个答案:

答案 0 :(得分:0)

使用您提供的测试用例,一种方法是使用split,splice和join。

for item in drugList {
  names1[item1.drugSubCategory]?.append(item1.drugName)  
  }

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

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

答案 1 :(得分: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);
}