【问题标题】:Issues with indexOf and lastIndexOf on substring - Get Part of URL from string子字符串上 indexOf 和 lastIndexOf 的问题 - 从字符串中获取部分 URL
【发布时间】:2012-12-30 19:49:30
【问题描述】:

我在以我想要的方式分解字符串时遇到了一些问题。我有一个这样的网址:

http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html

我正在尝试使用 substring 和 indexOf 而不是正则表达式来获取字符串上的 TARGETME 部分。这是我现在正在使用的函数:

 function lastPartofURL() {
    // Finding Url of Last Page, to hide Error Login Information
    var url = window.location;
    var filename = url.substring(url.lastIndexOf('/')+1);
    alert(filename);
}

但是,当我写这篇文章时,我的目标是“page.html”部分,所以这就是它返回的内容,但是我无法重新配置它来做我现在想做的事情。

如果可能,我希望它起源于字符串的开头而不是结尾,因为在我尝试定位的内容之前应该总是有一个 url,然后是一个目录,但我对两者都感兴趣解决方案。

这是一个执行类似操作的正则表达式,但它不安全(根据 JSLint),因此我不介意用更实用的东西替换它。

 /^.*\/.*\/TARGETME\/page.html.*/

【问题讨论】:

    标签: javascript jquery regex substring indexof


    【解决方案1】:

    正如其他人已经回答的那样,.split() 适合您的情况,但是假设您要返回 URL 的“最后一部分”(例如,也为 http://SomeAddress.whatever:portWhatever/dirA/DirB/TARGETME/page.html 返回“TARGETME”),那么您不能使用固定数字,而是取数组最后一个之前的项目:

    function BeforeLastPartofURL() {
        var url = window.location.href;
        var parts = url.split("/");
        var beforeLast = parts[parts.length - 2]; //keep in mind that since array starts with 0, last part is [length - 1]
        alert(beforeLast);
        return beforeLast;
    }
    

    【讨论】:

    • 这太棒了!这将是一个更强大的解决方案。谢谢!
    【解决方案2】:
     function lastPartofURL() {
        // Finding Url of Last Page, to hide Error Login Information
        var url = window.location;
        var arr = url.split('/');
    
        alert(arr[4]);
     }
    

    here

    【讨论】:

      【解决方案3】:

      试试这个

          function lastPartofURL() {
          // Finding Url of Last Page, to hide Error Login Information
          var url = window.location;
          var sIndex = url.lastIndexOf('/');
          var dIndex = url.lastIndexOf('.', sIndex);
          if (dotIndex == -1)
          {
              filename = url.substring(sIndex + 1);
          }
          else
          {
              filename = url.substring(sIndex + 1, dIndex);
          }
      
          alert(filename);
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用string.split()...

        function getPath() {
            var url = window.location;
            var path = url.split("/")[4];
            alert(path);
            return path;
        }
        

        我只推荐这种方法,因为你说你总是知道 URL 的格式。

        【讨论】:

        • 这是一个很好的解决方案!但是,就像您承认的那样,它依赖于始终相同的 url,因此它仅限于我现在的范围。现在非常简短和简洁!
        猜你喜欢
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 2016-06-09
        • 1970-01-01
        • 2015-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多