- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Get an Absolute Filename Path from a Relative Filename Path in Java
- Get an Absolute Filename Path from a Relative Filename with Path in Java
- How to get the last dirname/filename in a file path argument in Bash?
- Java Program to remove file information from a filename returning only its path component
- Java Program to remove path information from a filename returning only its file component
- Get Boot path from RuntimeMXBean in Java
- How to get left substring in MySQL from a column with file path? Display the entire file path string excluding the file name?
- How to get file name from a path in PHP?
- Get data from sessionStorage in JavaScript?
- Get key from value in JavaScript
- Form Object from string in JavaScript
- Get all digits from a string in Java
- Shortest path algorithms in Javascript
- Get global variable dynamically by name string in JavaScript?
- Get all substrings of a string in JavaScript recursively

Advertisements