Base64 encoding and decoding in client-side Javascript

前端 未结 14 2356
挽巷
挽巷 2020-11-22 04:27

Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding?

14条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:53

    Short and fast Base64 JavaScript Decode Function without Failsafe:

    function decode_base64 (s)
    {
        var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
        var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];
    
        for (z in n)
        {
            for (i = n[z][0]; i < n[z][1]; i++)
            {
                v.push(w(i));
            }
        }
        for (i = 0; i < 64; i++)
        {
            e[v[i]] = i;
        }
    
        for (i = 0; i < s.length; i+=72)
        {
            var b = 0, c, x, l = 0, o = s.substring(i, i+72);
            for (x = 0; x < o.length; x++)
            {
                c = e[o.charAt(x)];
                b = (b << 6) + c;
                l += 6;
                while (l >= 8)
                {
                    r += w((b >>> (l -= 8)) % 256);
                }
             }
        }
        return r;
    }
    

提交回复
热议问题