JavaScript中base64编码&解码

91 阅读1分钟
let Base64 = {
    encode(str) {
        // first we use encodeURIComponent to get percent-encoded UTF-8,
        // then we convert the percent encodings into raw bytes which
        // can be fed into btoa.
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
            function toSolidBytes(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
    },
    decode(str) {
        // Going backwards: from bytestream, to percent-encoding, to original string.
        return decodeURIComponent(atob(str).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
};

// 使用
 let encodedStr = Base64.encode('balabala');
 console.log(encodedStr); // YmFsYWJhbGE=
 
 let decodeStr = Base64.decode('YmFsYWJhbGE=');
 console.log(decodeStr); // balabala