【问题标题】:Javascript - how to remove .com or .net or .org from location.hrefJavascript - 如何从 location.href 中删除 .com 或 .net 或 .org
【发布时间】:2016-01-17 21:55:17
【问题描述】:

我需要从 location.href 中删除 .com 或任何域类型 例如:

sub.domain.com

我需要返回

sub.domain

谢谢!

【问题讨论】:

    标签: javascript regex replace dns


    【解决方案1】:

    您可以使用lastIndexOfsubstring

    var str = 'sub.domain.com';
    var end = str.lastIndexOf('.');
    return str.substring(0, end);
    

    一个完整的函数如下所示:

    function stripTopLevelDomain(var domain) {
      return domain.substring(0, domain.lastIndexOf('.'));
    }
    

    【讨论】:

      【解决方案2】:

      简单的方法:(不需要RegeEx)

      var url = "sub.domain.com"
      url = url.substring(0, url.lastIndexOf("."))
      
      document.write(url)

      【讨论】:

        【解决方案3】:

        简单的正则表达式解决方案:

        "sub.domain.com".replace(/([.]\w+)$/, '')
        

        [.] : the literal character .
        \w+ : match any word character [a-zA-Z0-9_]
        Quantifier: + Between one and unlimited times, as many times as possible
        $   : assert position at end of the string
        

        希望这会有所帮助。


        alert("sub.domain.com".replace(/([.]\w+)$/, ''));

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-14
          • 1970-01-01
          • 2019-07-11
          • 2022-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多