Get file from path javascript

Is there a way that I can get the last value (based on the '\' symbol) from a full path?

Example:

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.

Get file from path javascript

TylerH

21.2k59 gold badges74 silver badges93 bronze badges

asked Jan 8, 2009 at 5:43

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

This will handle both \ OR / in paths

mikeschuld

9221 gold badge11 silver badges24 bronze badges

answered Jan 8, 2009 at 5:48

nickfnickf

525k198 gold badges639 silver badges719 bronze badges

12

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 !

answered Aug 9, 2014 at 17:15

DanpeDanpe

18.2k19 gold badges91 silver badges130 bronze badges

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'

canon

39.3k9 gold badges71 silver badges94 bronze badges

answered Jun 28, 2015 at 20:43

RobLoachRobLoach

1,8731 gold badge11 silver badges5 bronze badges

1

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();

answered Jan 8, 2009 at 11:52

bobincebobince

518k102 gold badges645 silver badges825 bronze badges

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(/^.*(\\|\/|\:)/, '');

Get file from path javascript

answered Jun 26, 2009 at 21:12

user129661user129661

3293 silver badges2 bronze badges

1

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

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

Get file from path javascript

answered Jan 17, 2012 at 4:56

EpperlygEpperlyg

2272 silver badges2 bronze badges

0

Another one

var filename = fullPath.split(/[\\\/]/).pop();

Here split have a regular expression with a character class
The two characters have to be escaped with '\'

Or use array to split

var filename = fullPath.split(['/','\\']).pop();

It would be the way to dynamically push more separators into an array, if needed.
If fullPath is explicitly set by a string in your code it need to escape the backslash!
Like "C:\\Documents and Settings\\img\\recycled log.jpg"

answered May 3, 2019 at 18:17

2

Not more concise than nickf's answer, but this one directly "extracts" the answer instead of replacing unwanted parts with an empty string:

var filename = /([^\\]+)$/.exec(fullPath)[1];

answered Jan 9, 2009 at 3:55

Ates GoralAtes Goral

134k26 gold badges134 silver badges189 bronze badges

There’s no need to handle backslashes specially; most answers don’t handle search parameters.

The modern approach is to simply use the URL API and get the pathname property. The API normalizes backslashes to slashes.

In order to parse the resulting %20 to a space, simply pass it to decodeURIComponent.

const getFileName = (fileName) => new URL(fileName).pathname.split("/").pop();

// URLs need to have the scheme portion, e.g. `file://` or `https://`.
console.log(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg")); // "recycled%20log.jpg"
console.log(decodeURIComponent(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg"))); // "recycled log.jpg"
console.log(getFileName("https://example.com:443/path/to/file.png?size=480")); // "file.png"
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add a .filter(Boolean) before the .pop() if you always want the last non-empty part of the path (e.g. file.png from https://example.com/file.png/).

If you only have a relative URL but still simply want to get the file name, use the second argument of the URL constructor to pass a base origin. "https://example.com" suffices: new URL(fileName, "https://example.com"). It’s also possible to prepend "https://" to your fileName — the URL constructor accepts https://path/to/file.ext as a valid URL.

answered Apr 4, 2021 at 8:26

Sebastian SimonSebastian Simon

17k7 gold badges52 silver badges71 bronze badges

A question asking "get file name without extension" refer to here but no solution for that. Here is the solution modified from Bobbie's solution.

var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];

Get file from path javascript

Piyush

3,8378 gold badges35 silver badges67 bronze badges

answered Nov 21, 2014 at 2:20

Get file from path javascript

0

I use:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

It replaces the last \ so it also works with folders.

answered Jan 25, 2017 at 15:20

Get file from path javascript

pomberpomber

21.8k10 gold badges75 silver badges91 bronze badges

In Node.js, you can use the path.basename method

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

const filename = path.basename(file);
//=> 'file.txt'

answered Apr 23 at 13:23

Get file from path javascript

Sam HoustonSam Houston

3,0571 gold badge22 silver badges36 bronze badges

Little function to include in your project to determine the filename from a full path for Windows as well as GNU/Linux & UNIX absolute paths.

/**
 * @param {String} path Absolute path
 * @return {String} File name
 * @todo argument type checking during runtime
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
 * @example basename('/home/johndoe/github/my-package/webpack.config.js') // "webpack.config.js"
 * @example basename('C:\\Users\\johndoe\\github\\my-package\\webpack.config.js') // "webpack.config.js"
 */
function basename(path) {
  let separator = '/'

  const windowsSeparator = '\\'

  if (path.includes(windowsSeparator)) {
    separator = windowsSeparator
  }

  return path.slice(path.lastIndexOf(separator) + 1)
}

answered Aug 7, 2018 at 7:35

Amin NAIRIAmin NAIRI

2,05218 silver badges19 bronze badges

This solution is much simpler and generic, for both 'fileName' and 'path'.

parsePath = (path) => {
    // regex to split path (untile last / or \ to two groups '(.*[\\\/])' for path and '(.*)' (untile the end after the \ or / )for file name
    const regexPath = /^(?(.*[\\\/])?)(?.*)$/;

    const match = regexPath.exec(path);
    if (path && match) {
        return {
            path: match.groups.path,
            filename: match.groups.filename
        }
    }
    throw Error("Error parsing path");
}

// example
const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
parsePath(str);

answered Sep 30, 2019 at 16:33

HichamHicham

6066 silver badges17 bronze badges

2


Get file from path javascript

answered Jul 19, 2009 at 18:35

The complete answer is:


    
        Testing File Upload Inputs
        
    
    
        

Get file from path javascript

answered Jul 29, 2011 at 6:09


    
        Testing File Upload Inputs
        
    
    
        

Get file from path javascript

answered May 25, 2010 at 18:21

1

Successfully Script for your question ,Full Test