2

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?

4
  • 2
    If your string never ends with a /: 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). Commented Nov 3, 2020 at 14:10
  • 1
    Looks like you're already aware of the fact that .slice() "understands" a negative end. So why the loop? path_segs.slice(0, -1).join("/") Commented Nov 3, 2020 at 14:10
  • @Andreas good point, I haven't thought about it. I've always only used it for removing last element without really thinking how it works. Shame on me. Thank you! Commented Nov 3, 2020 at 14:16
  • @FelixKling thank you! The lastIndexOf is the method I was thinking about but couldn't find it. Commented Nov 3, 2020 at 14:16

2 Answers 2

2

Try this:

let mypath = "folder/subfolder/file";
const a = mypath.substring(0, mypath.lastIndexOf('/'));
console.log(a);
Sign up to request clarification or add additional context in comments.

1 Comment

It may be worth noting that you'll receive unexpected behavior if mypath is a folder path and ends with a /.
1

You can use path.parse. (Node.js only)

const path = require("path");
const somePath = "/some/weird/path";
const parsedPath = path.parse(somePath);
console.log(parsedPath.dir); // it will print /some/weird

parsedPath.dir is probably what you are looking for, bonus, it will work with paths in both windows and linux.

1 Comment

thanks, but I don't use Node, I'm working on strings in the UI.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.