代码之家  ›  专栏  ›  技术社区  ›  meallhour

捕获完全限定域名的“主机”部分的正确方法

  •  0
  • meallhour  · 技术社区  · 4 年前

    我有一个 hostName 字符串,该字符串可能是或可能不是完全限定的域名。

    hostName = host1.abc.com  OR
    
    hostName = host1
    

    万一 主机名 是一个完全限定的域名,那么我只需要捕获其中的第一部分 host

    host = host1
    

    "" 主机名

    const host = hostName.substring(0, hostName.indexOf('.'));
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   code99    4 年前

    const host = hostName.split('.')[0];

    否则

    const idx = hostName.indexOf('.');

    const host = idx > 0 ? hostName.substring(0, idx) : hostName;

    推荐文章