Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get filename from string path in JavaScript?
We need to write a function that takes in a string file path and returns the filename. Filename usually lives right at the very end of any path, although we can solve this problem using regex but there exists a simpler one-line solution to it using the string split() method of JavaScript and we will use the same here.
Let's say our file path is ?
"/app/base/controllers/filename.js"
Using split() Method
Following is the code to get file name from string path ?
const filePath = "/app/base/controllers/filename.js";
const extractFilename = (path) => {
const pathArray = path.split("/");
const lastIndex = pathArray.length - 1;
return pathArray[lastIndex];
};
console.log(extractFilename(filePath));
filename.js
One-Line Solution
We can simplify the above function to a single line using array indexing:
const filePath = "/app/base/controllers/filename.js";
const getFilename = (path) => path.split("/").pop();
console.log(getFilename(filePath));
console.log(getFilename("C:\Users\Documents\report.pdf"));
console.log(getFilename("simple-file.txt"));
filename.js report.pdf simple-file.txt
Handling Different Path Formats
For cross-platform compatibility, we can handle both Unix-style (/) and Windows-style (\) paths:
const getFilenameFromPath = (path) => {
return path.split(/[\/]/).pop();
};
console.log(getFilenameFromPath("/unix/style/path/file.js"));
console.log(getFilenameFromPath("C:\Windows\style\path\file.exe"));
console.log(getFilenameFromPath("mixed/path\formats\file.txt"));
file.js file.exe file.txt
Comparison of Methods
| Method | Cross-Platform | Code Length | Readability |
|---|---|---|---|
| split("/").pop() | Unix only | Short | High |
| split(/[\/]/).pop() | Yes | Short | Medium |
| Manual array indexing | Unix only | Medium | High |
Conclusion
The split() method with pop() provides a clean, one-line solution for extracting filenames from paths. Use the regex version for cross-platform compatibility when handling both Unix and Windows path formats.
