JVE999
JVE999

Reputation: 3517

How to remove the file path in javascript, leaving only the file name, regardless of filesystem

I have written a script that will remove everything after the last '\' from the file name, but I would like it to work in the circumstance that the user is uploading from a filesystem with forward slashes ('/') as well.

Here's the current code:

                var file1 = document.getElementById("file1");
                file1 = file1.value;
                var file_name1 = file1.split('\\').pop();

Essentially I just want the filename, rather than the directory.

Upvotes: 0

Views: 1041

Answers (3)

Jerry
Jerry

Reputation: 71538

Try using:

var file_name1 = file1.split(/[\\\/]/).pop();

This will split on the character class [\\\/] which means either \ or /.

Upvotes: 2

iConnor
iConnor

Reputation: 20189

Try this easy stuff

var str = 'http://stackoverflow.com/questions/5673752/searching-for-a-last-word-in-javascript.js';
    str = str.split(/[\\/]/).pop().split('.')[0];

console.log(str); // searching-for-a-last-word-in-javascript 

JSFiddle Demo Link


Or if you wan't the file extension aswell then just do this

var str = 'http://stackoverflow.com/questions/5673752/searching-for-a-last-word-in-javascript.js';
    str = str.split(/[\\/]/).pop(); // searching-for-a-last-word-in-javascript.js

JSFiddle Demo Link

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382092

You can adapt it like this using a regular expression to split :

var file_name1 = file1.split(/\/|\\/).pop();

Upvotes: 4

Related Questions