JavaScript 原生提供兩個 Base64 相關的方法
阿新 • • 發佈:2018-09-06
string clas 註意 ase com scrip enc asc style
JavaScript 原生提供兩個 Base64 相關的方法。
btoa()
:任意值轉為 Base64 編碼atob()
:Base64 編碼轉為原來的值
var string = ‘Hello World!‘; btoa(string) // "SGVsbG8gV29ybGQh" atob(‘SGVsbG8gV29ybGQh‘) // "Hello World!"
註意,這兩個方法不適合非 ASCII 碼的字符,會報錯。
btoa(‘你好‘) // 報錯
要將非 ASCII 碼字符轉為 Base64 編碼,必須中間插入一個轉碼環節,再使用這兩個方法。
function b64Encode(str) {return btoa(encodeURIComponent(str)); } function b64Decode(str) { return decodeURIComponent(atob(str)); } b64Encode(‘你好‘) // "JUU0JUJEJUEwJUU1JUE1JUJE" b64Decode(‘JUU0JUJEJUEwJUU1JUE1JUJE‘) // "你好"
JavaScript 原生提供兩個 Base64 相關的方法