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.

omega
  • 40,311
  • 81
  • 251
  • 474

8 Answers8

35

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
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);
David Fregoli
  • 3,377
  • 1
  • 19
  • 40
  • recursive function then :p – David Fregoli May 22 '13 at 15:12
  • @Matt This doesn't really look like a path. What should be the result ? – Denys Séguret May 22 '13 at 15:14
  • @dystroy It **can** be a (valid and working) path in server side and generating addresses dynamically... –  May 22 '13 at 15:16
  • @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. – Matt May 22 '13 at 15:20
  • 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](http://www.regular-expressions.info/). – Denys Séguret May 22 '13 at 16:02
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() );
PeterKA
  • 24,158
  • 5
  • 26
  • 48
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.

bdesham
  • 15,430
  • 13
  • 79
  • 123
  • @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. – bdesham May 22 '13 at 15:16
  • Yes, you are exactly right, but these paths `bar/` and `bar//` and `bar///` are the same, aren't? –  May 22 '13 at 15:19
  • 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. –  May 22 '13 at 15:23
  • 1
    On my website, which is hosted by Amazon S3, http://www.bdesham.info/ works fine while http://www.bdesham.info/// gives an error. – bdesham May 22 '13 at 15:24
  • big love! exactly what i was looking for – moeses Oct 02 '15 at 08:17
1

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
PersianIronwood
  • 639
  • 8
  • 19
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.

David Ziemann
  • 960
  • 1
  • 8
  • 22
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] : "";
LexLythius
  • 1,904
  • 1
  • 12
  • 20
  • I formatted your answer for you. Look at the buttons in the toolbar when editing. – Denys Séguret May 22 '13 at 15:20
  • @dystroy Thanks, I messed up the markdown from GitHub I guess. – LexLythius May 22 '13 at 15:28
  • 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 – LexLythius May 22 '13 at 22:46
0

A simple regexp can do the job

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

s.replace(/^.*\/([^\/]+\/)$/, "$1")
Rich Benner
  • 7,873
  • 9
  • 33
  • 39