Things I want to do
This JavaScript code retrieves the name of the parent folder from its full path.
Both URLs and file paths are valid.
I found a tool that returns the path from root to parent folder, but I couldn’t find one that returns only the parent folder, so I’m sharing it.
example
C:¥¥a\b\c\file.txt -> c
http://a.com/b/file.txt -> b
implementation
The implementation will be as follows:
This program splits the input by ‘/’ and ‘¥’ and returns the second-to-last string.
function getParentFolderName(filePath) {
const parts = filePath.split(/[\\/]/);
if (parts.length > 1) {
return parts[parts.length - 2];
} else {
return "";
}
}How to use
Call it as follows:
getParentFolderName(FULLPATH)Specific example
call
getParentFolderName("C:¥¥a\\b\\c\\file.txt")Return value
'c'Result
I was able to get the name of the parent folder from the full path using JavaScript.


コメント