【问题标题】:How to get the directory part of current URL in JavaScript?如何在 JavaScript 中获取当前 URL 的目录部分?
【发布时间】:2013-06-03 19:26:57
【问题描述】:

我正在尝试在网页顶部添加一个“返回目录”按钮,该按钮会将用户重定向到相同的 URL,但其中没有文件名。

例如,在查看 URL 时单击该按钮

http://example.com/somedir/button.html

会将您重定向到

http://example.com/somedir/

所以我创建了以下代码:

<html>
<body>

<input type="button"
value="back to dir"
onclick="top.location=document.URL.replace(/[^\\]*$/, '')">

</body>
</html>

但我缺少正确的代码,这会从 document.URL 中的当前 URL 中删除文件名

请问这里有人有什么好主意吗?

这里是 JSFiddle 链接:http://jsfiddle.net/afarber/PERBY/

而且我不想这一次使用 jQuery。

【问题讨论】:

    标签: javascript redirect directory


    【解决方案1】:

    console.log(new URL(document.URL));

    你会得到这样的所有对象:

    {
      href:"https://yy.xx.id/index.php/5351/user/private/images%20%282%29.jpeg?forcedownload=1",
    
      origin:"https://smi.kerjaindonesia.id", 
      protocol: "https:", 
      username: "", 
      password: "", 
      pathname: "index.php/5351/user/private/images%20%282%29.jpeg"  ,
      port: "" ,
      protocol: "https:",
      search: "?forcedownload=1"
    }
    

    【讨论】:

      【解决方案2】:

      以下获取目录,包括最后一个字符为斜杠的情况。

      document.URL.replace(/\/[^/]+\/?$/, '');
      

      这有效地说明了以下内容(假设可以按此顺序找到它们)

      1. \/:找一个“/”
      2. [^/]+:在它后面找到一个或多个不是“/”的字符
      3. \/?:在这些字符之后找到一个可选的“/”
      4. $: 找到字符串的结尾

      然后通过'' 删除这些,所以我们只剩下目录了。

      同样,这假设 存在一个斜线来标记目录,并且这不仅仅是一个 URL,其中唯一的斜线位于 http:// 内。

      【讨论】:

      • 我修改了这个以保留任何带有斜杠的路径组件(因此已经是目录的 URL 保持不变):window.location.href.replace(/\/[^/]+$/, '/')
      【解决方案3】:

      这种单线也适用:

      document.URL.split('/').slice(0, -1).join('/')
      

      【讨论】:

      • 虽然这种方法有效,但它比@abdul-rauf 发布的字符串解决方案慢得多
      【解决方案4】:

      试试这个document.URL.substr(0,document.URL.lastIndexOf('/'))

      它肯定会起作用!

      【讨论】:

      • 谢谢,这看起来不错 - 事件比我的正则表达式更好(我打错了...)
      • 不客气,如果效果好就给个赞,让其他人受益。
      • 如果当前 url 以斜杠结尾,这不起作用,因为它经常这样做。
      【解决方案5】:

      尝试以下方法,这会同时考虑 URL 以斜杠结尾和不以斜杠结尾的情况:

      var currUrl = document.URL,
          newUrl;
      if (currUrl.charAt(currUrl.length - 1) === '/') {
          newUrl = currUrl.slice(0, currUrl.lastIndexOf('/'));
          newUrl = newUrl.slice(0, newUrl.lastIndexOf('/')) + '/';
      } else {
          newUrl = currUrl.slice(0, currUrl.lastIndexOf('/')) + '/';
      }
      console.log(newUrl);
      

      【讨论】:

        【解决方案6】:
        /* to avoid query parameters, use pathname instead of href */
        var l = document.location.pathname.split('/');
        l.pop();
        console.log(document.location.origin + l.join('/'));
        

        【讨论】:

        • 仅供参考:document.location 已弃用,请改用 window.location
        猜你喜欢
        • 2013-10-27
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 2012-12-12
        • 1970-01-01
        相关资源
        最近更新 更多