原生 JS 的 Base64 转码

JavaScript 原生提供两个 Base64 相关的方法:

  • btoa():任意值转为 Base64 编码
  • atob():Base64 编码转为原来的值
注意:这两个方法不适合非 ASCII 码的字符,会报错。

要将非 ASCII 码字符转为 Base64 编码,必须中间插入一个转码环节:
  • encodeURIComponent()  该方法会转码除了语义字符之外的所有字符,即元字符也会被转码。
Base64 编码转为原来的值时,同样需要转码:
  • decodeURIComponent()  该方法是encodeURIComponent()方法的逆运算。
示例:
const str = "Hello, world!";
const strToBase64 = btoa(encodeURIComponent(str));
console.log(strToBase64); // SGVsbG8lMkMlMjB3b3JsZCE=
const base64ToStr = decodeURIComponent(atob(strToBase64));
console.log(base64ToStr); // Hello, world!

猜你喜欢

转载自www.cnblogs.com/WEB-PHP/p/10396223.html
今日推荐