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.
那么如何让他支持汉字呢?
console.log(window.decodeURIComponent(window.atob(btoaStr))); //解码结果 javascript,博客let str = 'javascript,博客';let btoaStr = window.btoa(window.encodeURIComponent(str)); //转码结果 amF2YXNjcmlwdCUyQyVFNSU4RCU5QSVFNSVBRSVBMg==console.log(btoaStr);
这就是btoa 和 atob的简单实用,希望对大家有所帮助。