简体   繁体   English

从路径中删除最后一个文件夹

[英]remove the last folder from a path

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));

loc returns as: loc返回为:

/public/html/signup/

dir returns as: dir返回为:

/public/html/signup

I want to remove the name of the folder too so i get back: 我也想删除文件夹的名称,所以我回来了:

/public/html/

What am I doing wrong? 我究竟做错了什么? Thanks! 谢谢!

Here you go. 干得好。 It's a universal solution so that you can strip as many folders as you want to - just pass something else than 1. 这是一种通用解决方案,因此您可以剥离任意数量的文件夹-只需传递1以外的内容即可。

var path = window.location.pathname.split("/");
var strippedPath = path.slice(0, path.length-1).join("/");

There is only one javascript native method that I know that remove an array element and return a deep copy of this modified list. 我知道只有一种JavaScript本机方法可以删除数组元素并返回此已修改列表的深层副本。 I could mention also reduce but this is out the scope here. 我可以提一下reduce但这不在这里讨论。

const new_path = path.split('/').filter((basename, index, array) => index !== array.length - (basename === '' ? 2 : 1)).join('/');

Filter is cool since it helps us to sort out basenames that are empties in a callback, equivalent to a spitted trailing slash within the path in our case. 过滤器很酷,因为它可以帮助我们对回调中的空基名进行排序,这相当于本例中路径中的随即斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM