最近写小程序,遇到小程序不支持函数atob,于是找了一个代码实现,代码如下:
function atob(input) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 === 1) {
throw new Error('InvalidLengthError');
}
for (let i = 0, len = str.length; i < len; i += 4) {
const a = chars.indexOf(str.charAt(i));
const b = chars.indexOf(str.charAt(i + 1));
const c = chars.indexOf(str.charAt(i + 2));
const d = chars.indexOf(str.charAt(i + 3));
const sum = (a << 18) | (b << 12) | (c << 6) | d;
output += String.fromCharCode((sum >> 16) & 0xFF, (sum >> 8) & 0xFF, sum & 0xFF);
}
return output;
}
此函数仅适用于ASCII字符集,在需要的地方调用它以解码base64字符串。