23

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

"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".

Is there an easy way through a built in function?

Thanks.

0

9 Answers 9

36

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.

Sign up to request clarification or add additional context in comments.

5 Comments

this will return bar/ if path has / in the end
@pXL fixed (bad copy-paste)
Note: (Title says: "How to get last folder name") The above will return about.html for i.e: /foo/bar/about.html
@RokoC.Buljan Right. But I think this was what OP asked for.
@dystroy yes gimme5! It was not criticism, just a N.B. :)
5

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)

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

5 Comments

recursive function then :p
@Matt This doesn't really look like a path. What should be the result ?
@dystroy It can be a (valid and working) path in server side and generating addresses dynamically...
@dystroy: it was mostly a lighthearted comment, but either an empty string or the "bar" I guess, whichever the OPs use case. The format still works on most (all?) webservers. Not sure if its part of a spec somewhere.
It looks like you'd like to know regular expressions. A good way to learn is to look at [regex] questions on SO and try to find the answer without looking at the other ones (at least until you tried enough). In the process you'd better have a look at this site.
3

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

Comments

2
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.

5 Comments

@NOX That path may or may not be equivalent to the path without trailing slashes; it depends on the web server. In general you can't simply ignore extra trailing slashes.
Yes, you are exactly right, but these paths bar/ and bar// and bar/// are the same, aren't?
I've never seen such that, can you show me an example? I tested in IIS and Apache web servers, and the paths are the same.
On my website, which is hosted by Amazon S3, bdesham.info works fine while bdesham.info// gives an error.
big love! exactly what i was looking for
2

I usually use the combination of split and pop in javascript, because I usually get the folder addres from aws s3 , it's already clean:

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

Comments

0

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

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.

Comments

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

First example yields "bar". Second example yields "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:

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

3 Comments

I formatted your answer for you. Look at the buttons in the toolbar when editing.
@dystroy Thanks, I messed up the markdown from GitHub I guess.
I think what you want to do is not correct, since the trailing slash does mean that the last segment is a directory (the only actual syntactical way to tell appart folders and files) and that may get you into trouble if you do something RESTful with this. I'll edit my answer, though
0

A simple regexp can do the job

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

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

Comments

0

Simple! Remove trailing slash, Split the path by slash / and get the last item with .pop() and the split by non word character

let getBar=path.replace(/\/$/,"").split("/").pop().split(/\W/)[0];

Comments

Your Answer

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.