Javascript - How to extract filename from a file input control
Nowadays there is a much simpler way:
var fileInput = document.getElementById('upload');
var filename = fileInput.files[0].name;
Assuming your <input type="file" > has an id of upload this should hopefully do the trick:
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
}
To split the string ({filepath}/{filename}) and get the file name you could use something like this:
str.split(/(\\|\/)/g).pop()
"The pop method removes the last element from an array and returns that value to the caller."
Mozilla Developer Network
Example:
from: "/home/user/file.txt".split(/(\\|\/)/g).pop()
you get: "file.txt"