0

This code accepts a path/to/folder or a path/to/folder/ (notice the trailing slash) and extracts the name of the last folder in the string, i.e.:

path = 'path/to/folder'.split('/');
folder = path.pop() || path.pop(); // taking care of trailing slash

// folder == 'folder'

I'm curious, is it possible to turn this into a one-liner? I would appreciate both regex and non-regex answers :)

As a side note, I just realized that my code doesn't know how to handle more than one trailing slash (like a typo) - so I'd appreciate it if you could take that into account as well.

Edit: I'm really hoping to see a non-regex answer

2
  • folder = path.split('/').slice(0, path.split('/').indexOf(''));, but this works only in modern browsers. Commented Jun 5, 2013 at 8:00
  • Clever - why not add it as an answer? Commented Jun 5, 2013 at 8:57

2 Answers 2

1

In modern browsers you can do something like this:

folder = (path + '/').split(/\/+|\\+/).slice(0, path.split(/\/+|\\+/).indexOf(''));

The code handles also backslashes, even mixed with slashes. A simple Fiddle.

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

3 Comments

By the way, this way you can work with any number of redundant slashes: (path + '/').split(/\/+|\\+/).slice(0, path.split(/\/+|\\+/).indexOf(''));
@pilau Ofcourse... I've added +s to my answer for future visitors, if it's OK?
Yeah, sure! I'll mark it as a right answer too... doesn't seem like I'll be getting any non-regex answers soon... Cheers for the best solution :)
1

I think this is what you want:

path = 'path/to/folder';
folder = path.match(/\/([^\/]+)[\/]*$/)[1]

Should work with or without trailing slash and with two slashes too.

4 Comments

Clean and simple :) Let's take it up a notch. Say this code is supposed to work on Windows and Unix machines - how would you handle the different slashes?
I think I'd find something similar to python's os.path.normpath or just replace "\" with "/" before doing a match() :)
Well we do have Node.js path library. But the bigger question is can it be done in a single line? ;)
Not really important - I like to learn alternative methods of doing things. It gets me familiar with other attitudes towards solving problems, and of course, expands my knowledge of JS. Lately I've been into one-liners. So that's the challenge!

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.