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 −


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];


The console output for this code will be −


Updated on: 18-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started