window.atob()与window.btoa()方法实现编码与解码
轉載于https://www.cnblogs.com/moqiutao/p/6280099.html
文章目錄
- window.atob() 與window.btoa()
- Unicode 字符串
- decodeURIComponent() 與encodeURIComponent()
- escape() 與unescape() 方法
一.window.atob() 與window.btoa()
WindowBase64.atob()?函數用來解碼一個已經被base-64編碼過的數據。你可以使用?window.btoa()?方法來編碼一個可能在傳輸過程中出現問題的數據,并且在接受數據之后,使用?window.atob() 方法來將數據解碼。例如:你可以把ASCII里面數值0到31的控制字符進行編碼,傳輸和解碼。
window.btoa():將ascii字符串或二進制數據轉換成一個base64編碼過的字符串,該方法不能直接作用于Unicode字符串.
語法:
var decodedData = window.atob(encodedData);例子:
var encodedData = window.btoa("Hello, world"); // 編碼 var decodedData = window.atob(encodedData); // 解碼其兼容性是主流瀏覽器,IE10及以上。
?
二.Unicode 字符串
在各瀏覽器中,使用?window.btoa?對Unicode字符串進行編碼都會觸發一個字符越界的異常.
先把Unicode字符串轉換為UTF-8編碼,可以解決這個問題, 代碼來自Johan Sundstr?m:
function utf8_to_b64( str ) {return window.btoa(unescape(encodeURIComponent( str ))); }function b64_to_utf8( str ) {return decodeURIComponent(escape(window.atob( str ))); }// Usage: utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU=" b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode" //譯者注:在js引擎內部,encodeURIComponent(str)相當于escape(unicodeToUTF8(str)) //所以可以推導出unicodeToUTF8(str)等同于unescape(encodeURIComponent(str))?
三.decodeURIComponent() 與encodeURIComponent()
這里用到了encodeURIComponent()與decodeURIComponent()方法,下面簡單介紹下:
decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。
下面給個例子:
<script type="text/javascript">var test1="http://www.w3school.com.cn/My first/"document.write(encodeURIComponent(test1)+ "<br />") document.write(decodeURIComponent(test1))</script>輸出的結果:
http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F http://www.w3school.com.cn/My first/下個例子, encodeURIComponent() 對 URI 進行編碼:
<script type="text/javascript">document.write(encodeURIComponent("http://www.w3school.com.cn")) document.write("<br />") document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/")) document.write("<br />") document.write(encodeURIComponent(",/?:@&=+$#"))</script>輸出結果:
http%3A%2F%2Fwww.w3school.com.cn http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F %2C%2F%3F%3A%40%26%3D%2B%24%23?
關于encodeURIComponent()與decodeURIComponent()的參考地址:
JavaScript decodeURIComponent() 函數與JavaScript encodeURIComponent() 函數
?
?四.escape() 與unescape() 方法
escape() 函數可對字符串進行編碼,這樣就可以在所有的計算機上讀取該字符串。
語法:escape(string)
返回值:已編碼的?string?的副本。其中某些字符被替換成了十六進制的轉義序列。
說明:該方法不會對 ASCII 字母和數字進行編碼,也不會對下面這些 ASCII 標點符號進行編碼: * @ - _ + . / 。其他所有的字符都會被轉義序列替換。
?
?參考地址:https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/btoa
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/atob
http://www.w3school.com.cn/jsref/jsref_escape.asp
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的window.atob()与window.btoa()方法实现编码与解码的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 村居民点建设情况报告3篇
- 下一篇: 关于开展干部谈心谈话工作总结3篇
