admin管理员组文章数量:1291107
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 acplish this?
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 acplish this?
Share Improve this question edited Aug 24, 2019 at 13:21 Zoe - Save the data dump 28.3k22 gold badges128 silver badges160 bronze badges asked Dec 1, 2012 at 23:35 MaverickMaverick 1,1235 gold badges16 silver badges30 bronze badges5 Answers
Reset to default 5Use .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);
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.
Could also use a regex:
function stripLastPiece(path) {
var matches = path.match(/^(.*\/)[^\/]+$/);
if (matches) {
return(matches[1]);
}
return(path);
}
Working example: http://jsfiddle/jfriend00/av7Mn/
If you want to get the first part of the array.
var firstWord = fullnamesaved.split(" ").shift();
This disregards all things after the space.
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
本文标签: JavascriptArray pop and get first part of arrayStack Overflow
版权声明:本文标题:Javascript - Array pop and get first part of array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741525221a2383426.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论