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:
Alternatively, here’s a TypeScript version:
Or a more concise one-liner:
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 bysplit
, which corresponds to the filename. The!
is used to assert that the result is a string, aspop
can return either astring
orundefined
.