简体   繁体   中英

How to make a Javascript string work with multiple file formats?

I'm trying to add gif emotes to a chat that my site has built in. At the moment it only works with .png file format.

I've tried replacing the .png'> part with .png | .gif'> .png | .gif'> and similar ways but didn't work.

emote: function(str) {
            var emo = ["biblethump", "kappa", "kreygasm", "pjsalt", "pogchamp", "fire", "rip", "failfish", "thumplove", "theilluminati", "cmonbruh", "lul", "ez", "bobtheshoplifter", "ree", "lambo", "fastercolorful", "kms", "glowbear", "pepelaserree", "feelsabdulman", "blobbanhammer", "success", "loveu"];
            for (var i = 0; i < emo.length; i++) {
                str = str.replace(new RegExp(emo[i] + "( |$)", "g"), "<img src='img/emotes/" + emo[i] + ".png'> ");
            }
            return str;
        },

HTML does not allow you to specify (png | gif). The reason for this is because the HTML img tag is simply making a request for the url you provide. Some solutions for this:

Have a lookup table in your javascript so you know what extension to use for a given emote:

const emoteExt = {
    biblethump: '.png',
    kappa: '.gif',
    kreygasm: '.png'
}

Your existing code would only need a small change:

"<img src='img/emotes/" + emo[i] + emoteExt[emo[i]] + "'> "

If you don't want to provide a lookup table on the client side, you can also handle this server side. The server that sends down the image can ignore the extension and send down whatever is available.

The server-side solution would not require code changes when new emotes or emote extensions are added but it requires a bit of know-how (and that you aren't using a static server).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM