由于 btoa 只支持 ASCII,在编码中文等其他字符时需要转义
let base64 = {
encode(str) {
return btoa(
encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode("0x" + p1);
})
);
},
decode(str) {
return decodeURIComponent(
atob(str)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
},
};
console.log(base64.encode("전라남도"));
console.log(base64.decode("7KCE652864Ko64+E"));