Maverick Maverick - 5 months ago 13
Javascript Question

Javascript - Array pop and get first part of array

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?

Answer

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);
Comments