jQuery find file extension (from string)

前端 未结 8 1142
半阙折子戏
半阙折子戏 2020-12-13 02:13

I was wondering if it was possible for jQuery to find a file extension based on a returned string?

A filename (string) will be passed to a function (openFile) and I

8条回答
  •  一整个雨季
    2020-12-13 03:07

    How about something like this.

    Test the live example: http://jsfiddle.net/6hBZU/1/

    It assumes that the string will always end with the extension:

    function openFile(file) {
        var extension = file.substr( (file.lastIndexOf('.') +1) );
        switch(extension) {
            case 'jpg':
            case 'png':
            case 'gif':
                alert('was jpg png gif');  // There's was a typo in the example where
            break;                         // the alert ended with pdf instead of gif.
            case 'zip':
            case 'rar':
                alert('was zip rar');
            break;
            case 'pdf':
                alert('was pdf');
            break;
            default:
                alert('who knows');
        }
    };
    
    openFile("somestring.png");
    

    EDIT: I mistakenly deleted part of the string in openFile("somestring.png");. Corrected. Had it in the Live Example, though.

提交回复
热议问题