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.
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.
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).
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.
The path. dirname() method returns the directories of a file path.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With