Base64 编码
在 HTML5 中新增了 atob 和 btoa 方法来支持 Base64 编码。它们的命名也很简单,b to a 和 a to b,即代表着编码和解码。
var a = “https://lin-xin.github.io”;
var b = btoa(a);
var c = atob(b);
console.log(a); // https://lin-xin.github.io
console.log(b); // aHR0cHM6Ly9saW4teGluLmdpdGh1Yi5pbw==
console.log©; // https://lin-xin.github.io**
btoa 方法对字符串 a 进行编码,不会改变 a 的值,返回一个编码后的值。
atob 方法对编码后的字符串进行解码。
但是参数中带中文,已经超出了8位ASCII编码的字符范围,浏览器就会报错。所以需要先对中文进行 encodeURIComponent 编码处理。
var a = “哈喽 世界”;
var b = btoa(encodeURIComponent(a));
var c = decodeURIComponent(atob(b));
console.log(b); // JUU1JTkzJTg4JUU1JTk2JUJEJTIwJUU0JUI4JTk2JUU3JTk1JThD
console.log©; // 哈喽 世界