I have a string that is a path of the folder
let mypath = "folder/subfolder/file"
in general, that can be any length. How can I get the path of the parent (in that case: let parentname = "folder/subfolder") the quickest. I could do:
let path_segs = mypath.split("/");
let parentname = "";
for (let i = 0; i < path_segs.length - 2; i++){
parentname += path_segs[i] + "/";
}
parentname.slice(0, -1);
return parentname;
but that seems to be long and inefficient. Is there any better way?
/:mypath.slice(0, mypath.lastIndexOf('/')). A shorter version of your array solution would be:let path_segs = mypath.split("/"); path_segs.pop(); let parentname = path_segs.join('/');(i.e. simply remove the last element and join the parts again)..slice()"understands" a negative end. So why the loop?path_segs.slice(0, -1).join("/")lastIndexOfis the method I was thinking about but couldn't find it.