[JavaScript] Get parent folder name from full path

This article can be read in about 2 minutes.
PR

The purpose 

I will get the parent folder name from a full path using JavaScript.

This works for both URLs and file paths.

I searched and found methods that return the path from the root to the parent folder, but none that returned only the parent folder name, so I’m sharing this.

Example

C:¥¥a\b\c\file.txt -> c

http://a.com/b/file.txt -> b

PR

Implementation

The implementation is as follows.

It 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 as follows

getParentFolderName(FULLPATH)

Example

Call

getParentFolderName("C:¥¥a\\b\\c\\file.txt")

Return

'c'
PR

Result

I was able to get the parent folder name from a full path using JavaScript.

comment

Copied title and URL