【问题标题】:FileName from url excluding querystring来自 url 的文件名,不包括查询字符串
【发布时间】:2011-05-17 18:22:41
【问题描述】:

我有一个网址:

http://www.xyz.com/a/test.jsp?a=b&c=d

我如何获得它的test.jsp

【问题讨论】:

  • /a\/(.*)\?/.exec('http://www.xyz.com/a/test.jsp?a=b&c=d')[1]

标签: javascript jquery


【解决方案1】:

应该这样做:

var path = document.location.pathname,
    file = path.substr(path.lastIndexOf('/'));

参考:document.locationsubstrlastIndexOf

【讨论】:

  • 这不会在查询字符串后删除。
  • @user: 无论如何,查询字符串不在pathname 中。它只返回路径。查看文档。
【解决方案2】:

我不会只告诉你答案,但我会给你方向。首先...去掉“?”之后的所有内容通过使用字符串实用程序和 location.href.status(这将为您提供查询字符串)。那么剩下的就是URL;获取最后一个“/”之后的所有内容(提示:lastindexof)。

【讨论】:

    【解决方案3】:

    使用正则表达式。

    var urlVal = 'http://www.xyz.com/a/test.jsp?a=b&c=d'; var 结果 = /a\/(.*)\?/.exec(urlVal)[1]

    正则表达式返回一个数组,使用[1]获取test.jsp

    【讨论】:

      【解决方案4】:

      此方法不依赖路径名:

          <script>
              var url = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
              var file_with_parameters = url.substr(url.lastIndexOf('/') + 1);
              var file = file_with_parameters.substr(0, file_with_parameters.lastIndexOf('?')); 
              // file now contains "test.jsp"
          </script>
      

      【讨论】:

      • 如果查询字符串中包含 /,这将不起作用。即:var url = '...www.xyz.com/a/test.jsp?a=b&c=d&file=/blah.html
      • 查询字符串中的斜杠需要编码,否则URL无效。
      • 除非在极少数情况下服务器专门配置为允许它们:stackoverflow.com/questions/462082/…
      • 我从来没有遇到过查询字符串中的斜杠问题...(在 Apache 上)。浏览器是否有可能自动转义它们?
      【解决方案5】:
      var your_link = "http://www.xyz.com/a/test.jsp?a=b&c=d";
      
      // strip the query from the link
      your_link = your_link.split("?");
      your_link = your_link[0];
      
      // get the the test.jsp or whatever is there
      var the_part_you_want = your_link.substring(your_link.lastIndexOf("/")+1);
      

      【讨论】:

        【解决方案6】:

        试试这个:

        /\/([^/]+)$/.exec(window.location.pathname)[1]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-27
          • 1970-01-01
          • 2022-01-13
          • 2012-10-23
          • 2012-09-27
          • 2013-04-09
          • 2012-03-31
          相关资源
          最近更新 更多