- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Following is the code to get file name from string path −
Example
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));
Output
The console output for this code will be −
filename.js
Advertisements
To Continue Learning Please Login
Login with Google