window.atob()與window.btoa()方法實現編碼與解碼

轉載於https://www.cnblogs.com/moqiutao/p/6280099.html

文章目錄

一.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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章