记录下原生JS的btoa和atob方法--js base64 编码与解码

1,321 阅读1分钟

b是binary二进制的简写,a是base64中a的简写,因为两个开头都是b,因此用a来代表base64 编码原理和此句话的引用

btoa

const obj = {
    foo: 'foo',
    baz: 'baz'
}
const base64 = btoa(unescape(encodeURIComponent(JSON.stringify(obj)))); // "eyJmb28iOiJmb28iLCJiYXoiOiJiYXoifQ=="

// data url
const dataUrl = 'data:application/json;charset=utf-8;base64,'.concat(base64); // "data:application/json;charset=utf-8;base64,eyJmb28iOiJmb28iLCJiYXoiOiJiYXoifQ=="

atob

const str = 'this is a test str';
const base64 = btoa(str); // "dGhpcyUyMGlzJTIwYSUyMHRlc3QlMjBzdHI="
const originalStr = decodeURIComponent(atob(b));  // "this is a test str"