原生 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!
相關文章
相關標籤/搜索