8

I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.

JavaScript

var x = path.split("/")
alert(path +' = ' +x.slice(0, -1));

Expected Result

/foo/bar/ = /foo/
/bar/foo/ = /bar/
/bar/foo/moo/ = /bar/foo/

2 Answers 2

18

Try:

let path = "/bar/foo/moo/";
let split = path.split("/");
let splicedStr = split.slice(0, split.length - 2).join("/") + "/";
console.log(splicedStr);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, just need to change var split to x
9

Try:

var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);

Output: /abc/def/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.