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

Updated on: 18-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements