42

我正在尝试删除 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.

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

4

5 回答 5

63

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

url.substring(0, url.lastIndexOf('/'));
于 2015-12-02T06:04:08.837 回答
47

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

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

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

于 2013-05-25T14:50:23.433 回答
3

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

path.normalize(path.join(thePath, '..'));
于 2020-11-11T10:43:08.257 回答
2

下面是一些正确处理/、 ""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);
}

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

于 2019-10-10T15:15:58.500 回答
0

坚持使用本机库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 的任何内容,但也许我只是看起来不够努力。

于 2020-10-25T21:17:04.320 回答