Javascript只返回主域名

Javascript return just primary domain name

本文关键字:域名 返回 Javascript      更新时间:2023-09-26

有没有一种懒惰的方法可以在不使用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

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

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

写正则表达式有很多方法,但就是其中之一

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

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

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