删除URL中的最后一个目录

pas*_*ein 19 javascript regex url replace path

我试图删除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.

我应该用什么正则表达式来做这件事?

Sha*_*rky 31

说明:按"/"分解,删除带有弹出的最后一个元素,再次使用"/"连接.

function RemoveLastDirectoryPartOf(the_url)
{
    var the_arr = the_url.split('/');
    the_arr.pop();
    return( the_arr.join('/') );
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这是不必要的低效。它会起作用,但会比 @Thrivan Mydeen 的答案慢得多。 (4认同)

Thi*_*een 19

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

url.substring(0, url.lastIndexOf('/'));
Run Code Online (Sandbox Code Playgroud)

  • 对于js:string removelastdir = url.substring(0,url.lastIndexOf('/')); (4认同)
  • 该解决方案优于更多赞成/接受的答案。只需查看它就很明显,但我还创建了一个简短的 jsperf 示例来展示这一点:https://jsperf.com/split-vs-lastindexof-2/1 (2认同)

小智 8

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

path.normalize(path.join(thePath, '..'));
Run Code Online (Sandbox Code Playgroud)