2

I have a path and I am trying to pop off everything after the last /, so 'folder' in this case, leaving the newpath as C://local/drive/folder/.

I tried to pop off the last / using pop(), but can't get the first part of the path to be the new path:

var path = C://local/drive/folder/folder
var newpath = path.split("/").pop();
var newpath = newpath[0]; //should be C://local/drive/folder/

How can I accomplish this?

Zoe - Save the data dump
28.4k22 gold badges130 silver badges163 bronze badges
asked Dec 1, 2012 at 23:35

5 Answers 5

5

Use .slice() instead of pop()

var newpath = path.split("/").slice(0, -1).join("/");

If you also need the last part, then just use .pop(), but first store the Array in a separate variable.

var parts = path.split("/");
var last = parts.pop();
var first = parts.join("/");

Now last has the last part, and first has everything before the last part.


Another solution is to use .lastIndexOf() on the string.

var idx = path.lastIndexOf("/");
var first = path.slice(0, idx);
var last = path.slice(idx + 1);
answered Dec 1, 2012 at 23:38
Sign up to request clarification or add additional context in comments.

Comments

2

Just replace the last statement to be like that:

var path = C://local/drive/folder/folder
path.split("/").pop(); // Discard the poped element.
var newpath = path.join("/"); // It will be C://local/drive/folder

A note about Array.pop: Each time you call the pop method it will return the last element and also it will remove it from the array.

answered Dec 1, 2012 at 23:45

Comments

1

Could also use a regex:

function stripLastPiece(path) {
 var matches = path.match(/^(.*\/)[^\/]+$/);
 if (matches) {
 return(matches[1]);
 }
 return(path);
}

Working example: http://jsfiddle.net/jfriend00/av7Mn/

answered Dec 1, 2012 at 23:41

Comments

1

If you want to get the first part of the array.

var firstWord = fullnamesaved.split(" ").shift();

This disregards all things after the space.

answered Jun 9, 2016 at 10:53

Comments

0
var foo = "C://local/drive/folder/folder";
foo.match(/(.+\/)[^\/]+$/);

would result in: ["C://local/drive/folder/folder", "C://local/drive/folder/"]

though i would prefer user1689607's answer

answered Dec 1, 2012 at 23:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.