【问题标题】:remove last directory in URL删除 URL 中的最后一个目录
【发布时间】:2013-05-20 23:21:20
【问题描述】:

我正在尝试删除 URL 的最后一个目录部分。我的网址如下所示:

https://my_ip_address:port/site.php?path=/path/to/my/folder.

点击按钮时,我想将其更改为

https://my_ip_address:port/site.php?path=/path/to/my。 (去掉最后一部分)。

我已经尝试过window.location.replace(/\/[A-Za-z0-9%]+$/, ""),结果是

https://my_ip_address:port/undefined.

我应该使用什么正则表达式来做到这一点?

【问题讨论】:

  • 您也可以添加/../。哈哈,开个玩笑,这是real deal
  • @HamZaDzCyber​​DeV 我忽略了路径中的. 以避免注入。但是感谢您的链接!
  • @HamZaDzCyber​​DeV 不知何故我不知道如何使用replacewindow.location.replace(/(.*)\/.*/,"\1"); 导致https://my_ip_address:port/(.*)\/.*/
  • 试试this$
  • 你必须使用正则表达式吗?还有其他方法。

标签: javascript regex url path replace


【解决方案1】:

另一种去除目录路径结尾的方法:

path.normalize(path.join(thePath, '..'));

【讨论】:

    【解决方案2】:

    坚持使用原生库,dirname 可能会有所帮助。


    node(后端)

    const path = require('path')
    let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
    console.log(path.dirname(n))
    console.log(path.dirname(n)+'/')
    

    输出是

    'https://my_ip_address:port/site.php?path=/path/to/my'
    'https://my_ip_address:port/site.php?path=/path/to/my'
    

    在 Firefox 浏览器中(参见MDN, Path Manupluation, OS.Path.dirname])

    let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
    console.log(OS.path.dirname(n))
    console.log(OS.path.dirname(n)+'/')
    
    

    抱歉,找不到任何关于 Chromium 的内容,但也许我只是看的不够仔细。

    【讨论】:

      【解决方案3】:

      下面是一些正确处理/、""、foo/foo的代码(分别返回/、""、foo/):

      function parentDirectory(dir: string): string {
        const lastSlash = dir.lastIndexOf('/');
        if (lastSlash === -1) {
          return dir;
        }
        if (lastSlash === 0) {
          return '/';
        }
        return dir.substring(0, lastSlash);
      }
      

      只需删除 Javascript 的 :strings。也许您想要不同的行为,但您至少应该考虑这些极端情况。

      【讨论】:

        【解决方案4】:

        通过使用此代码从 Url 链接中删除最后一个元素。

        url.substring(0, url.lastIndexOf('/'));
        

        【讨论】:

        • 对于 js: string removelastdir = url.substring(0, url.lastIndexOf('/'));
        • 此解决方案优于更多赞成/接受的答案。仅通过查看就很明显,但我还创建了一个简短的 jsperf 示例来展示这一点:jsperf.com/split-vs-lastindexof-2/1
        • 或者使用窗口:`window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'))`
        【解决方案5】:

        解释:用“/”分解,用pop去掉最后一个元素,用“/”重新加入。

        function RemoveLastDirectoryPartOf(the_url)
        {
            var the_arr = the_url.split('/');
            the_arr.pop();
            return( the_arr.join('/') );
        }
        

        见小提琴http://jsfiddle.net/GWr7U/

        【讨论】:

        • 这是不必要的低效。它会起作用,但它会比@Thrivan Mydeen 的回答慢得多。
        猜你喜欢
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多