Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following HTML / JS code:

<div class="file_upload">
        <input type="file" id="file_upload" name="file_upload" onchange="g();">
    </div>
<script>
    function g() {
        var fileName = document.getElementById("file_upload").value;
        fileName = fileName.substring(fileName.lastIndexOf('/')+1);
        alert(fileName);
    }
</script>

I want that after user upload a file, than the file name will displlay in alert the problem in this cide is that the path & the file name are diplayed and I want the file name only.

How can I fix it?

share|improve this question
    
How does the path look like? You're searching for "/" but in Windows, for example, you have to search for "\". –  MaxArt Jul 13 '13 at 9:59
    
Most likely you're testing on Windows and since the substring uses / to split off the filename, it won't match `\`. Quick solution would be: fileName = fileName.replace('\\', '/').substring(fileName.lastIndexOf('/') + 1); –  JimmiTh Jul 13 '13 at 9:59

1 Answer 1

up vote 1 down vote accepted

Try with this:

var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];

The path separator may be different with different OSes (for example, Windows and Linux), so you have to search for all of them. The most commons are / and \, and a simple regular expression can do the trick.

share|improve this answer
    
Thank you, it works great! –  Nave Tseva Jul 13 '13 at 10:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.