views:

2215

answers:

2

When a user selects a file in a web page I want to be able to extract just the filename.

I did try str.search function but it seems to fail when the file name is something like this: c:\uploads\ilike.this.file.jpg.

How can we extract just the file name without extension?

+2  A: 
var pieces = str.split('\\');
var filename = pieces[pieces.length-1];
TM
This assumes that the user is running Windows. Other operating systems use different file path seperators.
David Dorward
Would you need to check for the '/' character as well for non-Windows users e.g. if (!pieces) { str.split('/'); }? Nice simple solution though +1
Ian Oxley
IIRC, IE is the only browser that gives the full path of the file anyway... You won't need to split on other browsers like Firefox, so it still works.Although I admit I haven't tried EVERY linux/unix browser.
TM
str.split(/(\\|\/)/g); for windows and *nix
Tracker1
+2  A: 

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);
}
Ian Oxley
Thanks this seems to work well, but I just want filename without extension. How can I do that in above code.
Yogi Yang 007
I added these two lines of code to extract just the file name without extension:"filename = filename.substring(0,filename.length-4); filename = filename.toLowerCase();"
Yogi Yang 007