1. 程式人生 > >原生 JS 的 Base64 轉碼

原生 JS 的 Base64 轉碼

kml script one 一個 中間 示例 style 轉碼 16px

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!

原生 JS 的 Base64 轉碼