Get only file name from file input in Internet Explorer

I need to return only the file name from the input HTML file.

<input type="file" id="whatever" /> 

The JavaScript code used to get the file name:

 document.getElementById("whatever").value; 

In firefox, it gives only the file name that I want, but in IE I get the full path.

I think string manipulation is the only way to get the name.

What would be the easiest / shortest way to get just a name (extension too) in JavaScript? Thanks.

+6
source share
3 answers

You can try this

 var path = document.getElementById("whatever").value; var fileName = path.match(/[^\/\\]+$/); console.log(fileName); 
+17
source

Hope this works.

 var fullFileName = document.getElementById("whatever").value; var fileName = fullFileName.substr(fullFileName.lastIndexOf("\\")+1, fullFileName.length); 

Here is the script for this feed

+2
source
 var path = document.getElementById("whatever").value; var filename = path.substring(path.lastIndexOf("/") + 1); 

This will give you everything after the last / , but also compatible with the lack of / s. If you also need to deal with \ as an excellent path separator, you can always use this in the first place:

 path.replace(/\\/g, "/") 
0
source

All Articles