How to get a file name from path in JavaScript

When working with JavaScript, interacting with file paths and directories is common. As such, the desire to get as much detail about the file types is very important.

So, how can you get a file name from a path in JavaScript? Well, we can do this relatively easily using native JavaScript methods.

Let say we have a  path like so:

C:\Documents\img\tommy_vercetti.jpg

We can get tommy_vercetti.jpg by using JavaScript’s replace() method:

var filename = path.replace(/^.*[\\\/]/, '')
// tommy_vercetti.jpg

But wait, there’s actually a more performant way of doing so using JavaScript’s native methods .split() and.pop() 

const getPath = (str) => {
    return str.split('\\').pop().split('/').pop();
}
// tommy_vercetti.jpg

 

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.