Search code examples
javascriptsubstringlastindexof

Can't unserstand how this example work. lastIndexOf() Method


I was looking at this example that get the name of a file after you select it in your pc.

I writing becuase I don't understand, how in this case lastIndexOf() works!

<script>
        $('#browseFile').change(function() {
            var filename = $(this).val();
            var lastIndex = filename.lastIndexOf("\\");
            if (lastIndex >= 0) {
                filename = filename.substring(lastIndex + 1);
            }
            $('#filename').val(filename);
       });
</script>

I know that lastIndexOf count how many chars you have before a specified string so for example:

var phrase = "look at the sea";
var result phrase.lastIndexOf("sea");

will return 13, but why in the first example I posted if (lastIndex >= 0) then we know the name of the file?


Solution

  • var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    

    What this does is to find the last backslash. If one exists (if (lastIndex >= 0)), then we remove everything leading up to it using substring. In other words, the code removes the path before a file name.

    Edit: I'm an idiot and messed up the substring syntax. Corrected.