Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 347
omega Avatar asked May 22 '13 15:05

omega


People also ask

How to get Current directory path in js?

Using __dirname in a Node script will return the path of the folder where the current JavaScript file resides. Using ./ will give you the current working directory.

How do I find the last path of a URL?

We identify the index of the last / in the path, calling lastIndexOf('/') on the thePath string. Then we pass that to the substring() method we call on the same thePath string. This will return a new string that starts from the position of the last / , + 1 (otherwise we'd also get the / back).

How to get directory name in node js?

console. log("Current directory:", __dirname); The variable will print the path to the directory, starting from the root directory. And just like that, you can get the current working directory in NodeJS.

What is path dirname?

The path. dirname() method returns the directories of a file path.


2 Answers

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.

like image 190
Denys Séguret Avatar answered Sep 20 '22 21:09

Denys Séguret


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);
like image 24
David Fregoli Avatar answered Sep 17 '22 21:09

David Fregoli