سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

lastIndexOf returns:

the zero-based index position of the last occurrence of a specified Unicode character or string

In your example we are looking for the last \ in the path and then taking the next part in the path which is the file name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top