最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return last directory in a path - Stack Overflow

programmeradmin6浏览0评论

I am trying to return the last directory in a path. For instance, for the following path, I wish to return "third". My paths always start with no slashes and end with a slash. If the path is empty, I wish to return an empty string.

first/second/third/

Below is my attempt. Any remendations on a better way?

var path='first/second/third/';
path1=path.substring(0, path.length - 1);
path2=path1.substr(path1.lastIndexOf('/') + 1);

I am trying to return the last directory in a path. For instance, for the following path, I wish to return "third". My paths always start with no slashes and end with a slash. If the path is empty, I wish to return an empty string.

first/second/third/

Below is my attempt. Any remendations on a better way?

var path='first/second/third/';
path1=path.substring(0, path.length - 1);
path2=path1.substr(path1.lastIndexOf('/') + 1);
Share Improve this question asked Oct 11, 2013 at 17:17 user1032531user1032531 26.4k75 gold badges245 silver badges416 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 4

The lighter way of achieving such thing :)

// Remove trailing slash and split by slashes, then pick the last occurrence
path = path.replace(/\/$/, "").split("/").pop();
var path='first/second/third/';
var path2 = path.split('/');
path2 = path2[path2.length-2];

-2 because the last one is empty because of the last slash.

split your way to success

var parts = path.split("/");
var last = parts[parts.length-1];

Of course, you'll need to decide what to do on fist/path/to/last vs. first/path/to/last/. Your usecases might require handling either one or both.

Try splitting the path and if the last directory is undefined (because the path is empty) use an empty string:

var path='first/second/third/';
var parts = path.split("/");
var path1 = parts[parts.length - 2] || ""

Maybe split would be better/cleaner choice here..

var directories = path.split("/");
var lastDir     = directories[directories.length - 1]

Try this,

var path='first/second/third/';
path.match(/([^\/]*)\/*$/)[1]; // return third

Here's a function segment that will take a url like string and return a specific part of it (using 1 counting, not 0). So, segment(str, 1) return first, and segment(str, 3) returns third. It also includes a trim function to strip off nasty preceding or trailing slashes which would cause empty items in the segments array... but maybe you want those so in that case just use return str.split... in the segment function.

var trim = function (str, charset) {
    charset = charset || "\s";

    var regex = new RegExp("^[" + charset + "]+|[" + charset + "]+$", "g")
    return str.replace(regex, "");
};

var segment = function (str, offset) {
    return trim(str, '/').split('/')[offset - 1];
}
发布评论

评论列表(0)

  1. 暂无评论