Reputation: 3517
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
Reputation: 71538
Try using:
var file_name1 = file1.split(/[\\\/]/).pop();
This will split on the character class [\\\/]
which means either \
or /
.
Upvotes: 2
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
Reputation: 382092
You can adapt it like this using a regular expression to split :
var file_name1 = file1.split(/\/|\\/).pop();
Upvotes: 4