How to get the file name from a full path using JavaScript?

How to get the file name from a full path using JavaScript?

Is there a way that I can get the last value (based on the ‘\’ symbol) from a full path?
C:\Documents and Settings\img\recycled log.jpg
With this case, I just want to get recycled log.jpg from the full path in JavaScript.


Solution 1:

var filename = fullPath.replace(/^.*[\\\/]/, '')

This will handle both \ OR / in paths

Solution 2:

Just for the sake of performance, I tested all the answers given here:

var substringTest = function (str) {
    return str.substring(str.lastIndexOf('/')+1);

var replaceTest = function (str) {
    return str.replace(/^.*(\\|\/|\:)/, '');

var execTest = function (str) {
    return /([^\\]+)$/.exec(str)[1];

var splitTest = function (str) {
    return str.split('\\').pop().split('/').pop();

substringTest took   0.09508600000000023ms
replaceTest   took   0.049203000000000004ms
execTest      took   0.04859899999999939ms
splitTest     took   0.02505500000000005ms

And the winner is the Split and Pop style answer, Thanks to bobince !

Solution 3:

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different…

If it’s a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both ‘\’ (Windows) and ‘/’ (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here’s a non-RegExp version for extra fun:

var leafname= pathname.split('\\').pop().split('/').pop();

Solution 4:

In Node.js, you can use Path’s parse module

var path = require('path');
var file = '/home/user/dir/file.txt';

var filename = path.parse(file).base;
//=> 'file.txt'

Solution 5:

Ates, your solution doesn’t protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

bobince, here’s a version of nickf’s that handles DOS, POSIX, and HFS path delimiters (and empty strings):

return fullPath.replace(/^.*(\\|\/|\:)/, '');

Solution 6:

The following line of JavaScript code will give you the file name.

var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);

Related:  Update all clients using