문제

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