omega omega - 7 months ago 26
Javascript Question

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

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.

Answer

Use the power of the regular expression :

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