如何进行Base64转码解码
- 转码 window.btoa()
- 解码 window.atob()
// 可以编码、传输和解码操作各种字符,比如0-31的ASCII码值
var str = 'Hello, smart, beautiful and lovely girl';
window.btoa(str)
//转码结果 'SGVsbG8sIHNtYXJ0LCBiZWF1dGlmdWwgYW5kIGxvdmVseSBnaXJs'
window.atob("SGVsbG8sIHNtYXJ0LCBiZWF1dGlmdWwgYW5kIGxvdmVseSBnaXJs")
//解码结果 "Hello, smart, beautiful and lovely girl"
但是如果包含中文就会报错
var str = "Hello,钢筋bb";
ncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. at <anonymous>:1:8
要编码的字符串包含拉丁范围之外的字符
这时候可以用
- 转码 window.encodeURIComponent()
- 解码 window.decodeURIComponent
encodeURIComponent 转义除了如下所示外的所有字符:
不转义的字符:A-Z a-z 0-9 - _ . ! ~ * ' ( )
为了避免服务器收到不可预知的请求,对任何用户输入的作为URI部分的内容都需要用encodeURIComponent进行转义
var str = "Hello,钢筋bb";
window.btoa(window.encodeURIComponent(str))
//转码结果 'SGVsbG8lRUYlQkMlOEMlRTklOTIlQTIlRTclQUQlOEJiYg=='
window.decodeURIComponent(window.atob('SGVsbG8lRUYlQkMlOEMlRTklOTIlQTIlRTclQUQlOEJiYg=='))
//解码结果 'Hello,钢筋bb'