javascript 如何从javascript中的文件夹路径获取最后一个文件夹名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16695369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:39:41  来源:igfitidea点击:

How to get last folder name from folder path in javascript?

javascriptjquery

提问by omega

In javascript/jquery, given a path to a folder like:

在 javascript/jquery 中,给定一个文件夹的路径,如:

"http://www.blah/foo/bar/" 

or

或者

"http://www.blah/foo/bar" (this one doesn't have a slash in the end)

How can you extract the name of the last folder? In this case it would be "bar".

如何提取最后一个文件夹的名称?在这种情况下,它将是"bar".

Is there an easy way through a built in function?

是否有通过内置函数的简单方法?

Thanks.

谢谢。

回答by Denys Séguret

Use the power of the regular expression :

使用正则表达式的力量:

var name = path.match(/([^\/]*)\/*$/)[1]

Notice that this isn't the last "folder" (which isn't defined in your case and in the general case of an URL) but the last path token.

请注意,这不是最后一个“文件夹”(在您的情况和 URL 的一般情况下未定义),而是最后一个路径标记。

回答by David Fregoli

Use regular expressions! or:

使用正则表达式!或者:

var arr = 'http://www.blah/foo/bar/'.split('/');
var last = arr[arr.length-1] || arr[arr.length-2];

this accounts for 'http://www.blah/foo/bar////' :p (or crashes the browser)

这说明了“ http://www.blah/foo/bar////” :p (或使浏览器崩溃)

var arr = 'http://www.blah/foo/bar/////'.split('/');
var last = (function trololol(i) {
  return arr[i] || trololol(i-1);
})(arr.length-1);

回答by PeterKA

Take a look at this:

看看这个:

var lastFolder = location.href.split('/').filter(function(el) { 
    return el.trim().length > 0; 
}).pop();

alert( location.href.split('/').filter(function(el) { return el.trim().length > 0; }).pop() );
alert( location.href );

var test = "http://www.blah/foo/bar/" ;
alert( test.split('/').filter(function(el) { return el.trim().length > 0; }).pop() );

回答by bdesham

var myString = "http://www.blah/foo/bar";
var pathElements = myString.replace(/\/$/, '').split('/');
var lastFolder = pathElements[pathElements.length - 1];

This is pure JavaScript and doesn't need jQuery.

这是纯 JavaScript,不需要 jQuery。

回答by PersianIronwood

I usually use the combination of splitand popin javascript, because I usually get the folder addres from aws s3 , it's already clean:

我通常使用的组合split,并pop在JavaScript中,因为我通常会从AWS S3文件夹ADDRES,它已经干净:

const teststring = 'image_1/ArtService/GB/ART-123/dependants/ASM-123';
const folder = teststring.split('/').pop();
console.log('folder:', folder);// ASM-123

回答by Marinoshu

A simple regexp can do the job

一个简单的正则表达式就可以完成这项工作

var s = "toto1/toto2/toto3toto1/totofinale/";

s.replace(/^.*\/([^\/]+\/)$/, "")

回答by David Ziemann

You can split the string into a list and grab the last element in the list via a function.

您可以将字符串拆分为列表并通过函数获取列表中的最后一个元素。

function checkString(stringToCheck) {
    var list1 = stringToCheck.split('/');
    if (list1[list1.length - 1].length < 1) {
        var item = list1[list1.length - 2]
    } else {
       var item = list1[list1.length - 1];
    }
    $('#results').append('Last Folder in '+stringToCheck+': <b>'+item+'</b><br>');

}

}

From there you can find the last actual element.

从那里您可以找到最后一个实际元素。

JSFiddle Example

JSFiddle 示例

While it may not be the most elegant answer, it seems to be the easiest to understand for someone that might not know regular expressions.

虽然它可能不是最优雅的答案,但对于可能不了解正则表达式的人来说,它似乎是最容易理解的。

Updated JSFiddle to display the results.

更新了 JSFiddle 以显示结果。

回答by LexLythius

var str = "...";
var segments = str.split("/");
var lastDir = (segments.length > 1) ? segments[segments.length - 2] : "";

First example yields "bar". Second example yields "foo".

第一个例子产生“bar”。第二个例子产生“foo”。

If you want to disregard trailing slash and consider the last segment as a folder as well, then a slight tweak to @bdesham's RegExp does the trick:

如果您想忽略尾部斜杠并将最后一段也视为文件夹,那么对@bdesham 的 RegExp 稍作调整即可解决问题:

var segments = str.replace(/\/+$/, '').split('/');
var lastDir = (segments.length > 0) ? segments[segments.length - 1] : "";