Hướng dẫn get file extension javascript - lấy phần mở rộng tệp javascript

Tôi chắc chắn rằng ai đó có thể, và sẽ, thu nhỏ và/hoặc tối ưu hóa mã của tôi trong tương lai. Nhưng, ngay bây giờ, tôi tự tin 200% rằng mã của tôi hoạt động trong mọi tình huống duy nhất (ví dụ: chỉ với tên tệp, với URL tương đối, gốc và URL tuyệt đối, với các thẻ #, với chuỗi truy vấn ?, chuỗi, Và bất cứ điều gì khác bạn có thể quyết định ném vào nó), hoàn hảo và với độ chính xác điểm pin.

Để chứng minh, hãy truy cập: https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php

Đây là jsfiddle: https://jsfiddle.net/jamesandersonjr/ffcdd5z3/

Không quá tự tin, hay thổi kèn của riêng tôi, nhưng tôi chưa thấy bất kỳ khối mã nào cho nhiệm vụ này (tìm phần mở rộng tệp 'chính xác', giữa một pin của các đối số đầu vào ____3 khác nhau) hoạt động tốt như điều này.

Lưu ý: Theo thiết kế, nếu một phần mở rộng tệp không tồn tại cho chuỗi đầu vào đã cho, nó chỉ cần trả về một chuỗi trống "", không phải là lỗi, cũng không phải là thông báo lỗi. By design, if a file extension doesn't exist for the given input string, it simply returns a blank string "", not an error, nor an error message.

Nó có hai đối số:

  • Chuỗi: FILENAMEORURL (Tự giải thích) (self-explanatory)

  • Boolean: ShowunixDotFiles (có hiển thị các tệp bắt đầu bằng dấu chấm ".") (Whether or Not to show files that begin with a dot ".")

Lưu ý (2): Nếu bạn thích mã của tôi, hãy chắc chắn thêm nó vào thư viện JS và/hoặc repo của bạn, vì tôi đã làm việc chăm chỉ để hoàn thiện nó, và sẽ thật xấu hổ khi lãng phí. Vì vậy, không có gì khó chịu, đây là: If you like my code, be sure to add it to your js library's, and/or repo's, because I worked hard on perfecting it, and it would be a shame to go to waste. So, without further ado, here it is:

function getFileExtension(fileNameOrURL, showUnixDotFiles)
    {
        /* First, let's declare some preliminary variables we'll need later on. */
        var fileName;
        var fileExt;
        
        /* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */
        var hiddenLink = document.createElement('a');
        
        /* Just for fun, we'll add a CSS attribute of [ style.display = "none" ]. Remember: You can never be too sure! */
        hiddenLink.style.display = "none";
        
        /* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */
        hiddenLink.setAttribute('href', fileNameOrURL);
        
        /* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/ 
        fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, ""); /* First, let's strip out the protocol, if there is one. */
        fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, ""); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */
        fileNameOrURL = fileNameOrURL.replace(":" + hiddenLink.port, ""); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */  
        
        /* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */
        
        /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */ 
        
        /* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */
        fileNameOrURL = fileNameOrURL.split('?')[0];

        /* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */
        fileNameOrURL = fileNameOrURL.split('#')[0];

        /* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */
        fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf("/"));

        /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */ 

        /* Now, 'fileNameOrURL' should just be 'fileName' */
        fileName = fileNameOrURL;
        
        /* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */  
        if ( showUnixDotFiles == false )
            {
                /* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */
                if ( fileName.startsWith(".") )
                    {
                        /* If so, we return a blank string to the function caller. Our job here, is done! */
                        return "";
                    };
            };
        
        /* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */
        fileExt = fileName.substr(1 + fileName.lastIndexOf("."));

        /* Now that we've discovered the correct file extension, let's return it to the function caller. */
        return fileExt;
    };

Vui thích! Bạn khá hoan nghênh!: