1 min read

Basename Function in JavaScript/TypeScript

In my application, I need to extract only the filename from a given full file path. While PHP provides a built-in function basename for this purpose, JavaScript does not have an equivalent built-in function.

To achieve this in JavaScript, we can create a custom function:

function basename(path) {
  return path.split(/[\\/]/).pop();
}

Alternatively, here’s a TypeScript version:

const basename = (path: string): string => {
  return path.split(/[\\/]/).pop()!;
};

Or a more concise one-liner:

const basename = (path: string): string => path.split(/[\\/]/).pop()!;

Explanation of the code:

  • path: This is the original or full path value.
  • split(/[\\/]/): This splits the path string using either / or \ as the directory separator, accommodating both Unix and Windows styles.
  • pop()!: This retrieves the last element from the array returned by split, which corresponds to the filename. The ! is used to assert that the result is a string, as pop can return either a string or undefined.