1. 程式人生 > >javascript使用btoa和atob來進行Base64轉碼和解碼

javascript使用btoa和atob來進行Base64轉碼和解碼

ring scrip str pre AS sid encode highlight nbsp

javascript中如何使用Base64轉碼

 let str = ‘javascript‘;
 let btoaStr = window.btoa(str);  //轉碼結果 amF2YXNjcmlwdA==
 console.log(btoaStr);
 console.log(window.atob(btoaStr)); //解碼結果 javascript

Base64轉碼的對象只能是字符串,

var str = "China,中國"; 
window.btoa(str) ;

// 報錯 Uncaught DOMException: Failed to execute ‘btoa‘ on ‘Window‘: The string to be encoded contains characters outside of the Latin1 range.

那麽如何讓他支持漢字呢?

let str = ‘javascript,博客‘;
let btoaStr = window.btoa(window.encodeURIComponent(str));  //轉碼結果  amF2YXNjcmlwdCUyQyVFNSU4RCU5QSVFNSVBRSVBMg==
console.log(btoaStr);
console.log(window.decodeURIComponent(window.atob(btoaStr))); //解碼結果 javascript,博客

這就是btoa 和 atob的簡單實用,希望對大家有所幫助。

javascript使用btoa和atob來進行Base64轉碼和解碼