js base64的轉碼與解碼


使用方法window.btoa 將字符串轉為base64編碼

使用方法window.atob 將base64編碼轉為js字符串

 

 

var string = “Hello World”

let base64 = window.btoa(string)

let str = window.atob(base64)

 

  

注意:

javascript中的字符的實現一般是16位無符號整數

 

(http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.1)

 

 

window.btoa接收的string是8位的,所以,如果是超過8位的,比如unicode編碼 中的中文就會報錯 

(

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it willprobablybreak. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.
  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

)

 

let str = ‘我叫

window.btoa(str) // InvalidCharacterError: String contains an invalid character

 

可以先將unicode text轉換為utf-8編碼(encodeURIComponent),然后使用base64編碼,解碼的時候再轉換回來,就能得到原先的text

 

注意:

encodeURIComponent的轉義范圍比encodeURI更大


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM