在前端開發中,經常需要將字元串轉換為Base64編碼,以便進行數據傳輸或存儲。本文將介紹在JavaScript中如何將字元串轉換為Base64編碼,以及一些常用技巧。
一、什麼是Base64編碼
Base64是一種基於64個可列印字元來表示二進位數據的編碼方式。它使用特定的編碼表,將每3個8位的字元轉換為4個6位的字元,所以每個Base64字元表示的實際位數是6位,而不是8位。這種編碼方式主要用於電子郵件、HTTP等協議中傳輸較小的二進位數據。
二、字元串轉換為Base64編碼
在JavaScript中,可以使用WindowBase64.btoa()方法將一個字元串轉換為Base64編碼:
let str = 'Hello, World!'; let base64Str = window.btoa(str); console.log(base64Str); // SGVsbG8sIFdvcmxkIQ==
在上面的例子中,字元串”Hello, World!”被轉換為了Base64編碼”SGVsbG8sIFdvcmxkIQ==”。需要注意的是,WindowBase64.btoa()方法只能處理ASCII編碼的字元,不能處理Unicode編碼的字元。
三、Base64編碼轉換為字元串
與WindowBase64.btoa()方法對應的是WindowBase64.atob()方法,可以用來將Base64編碼轉換為字元串:
let base64Str = 'SGVsbG8sIFdvcmxkIQ=='; let str = window.atob(base64Str); console.log(str); // Hello, World!
需要注意的是,WindowBase64.atob()方法只能處理ASCII編碼的字元,如果有非ASCII編碼的字元,會拋出一個異常。
四、常用技巧
1. 封裝為函數
我們可以封裝一個函數,方便在代碼中多次調用:
function stringToBase64(str) { return window.btoa(str); } function base64ToString(base64Str) { return window.atob(base64Str); } let str = 'Hello, World!'; let base64Str = stringToBase64(str); console.log(base64Str); // SGVsbG8sIFdvcmxkIQ== let str2 = base64ToString(base64Str); console.log(str2); // Hello, World!
2. 處理Unicode字元
如果需要處理Unicode編碼的字元,可以使用encodeURIComponent()和decodeURIComponent()方法來轉換:
let str = '中文'; let base64Str = window.btoa(encodeURIComponent(str)); console.log(base64Str); // JUU0JUFEJTk= let str2 = decodeURIComponent(window.atob(base64Str)); console.log(str2); // 中文
在上面的例子中,字元串”中文”被轉換為了Base64編碼”JUU0JUFEJTk=”。需要注意的是,在使用decodeURIComponent()方法時,需要先用WindowBase64.atob()將Base64編碼轉換為字元串。
3. 處理二進位數據
如果需要處理二進位數據,可以使用Uint8Array數組來進行轉換:
let bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21]); let base64Str = btoa(String.fromCharCode.apply(null, bytes)); console.log(base64Str); // SGVsbG8sIFdvcmxkIQ==
在上面的例子中,一個包含十三個位元組的數組被轉換為了Base64編碼”SGVsbG8sIFdvcmxkIQ==”。需要注意的是,在使用Uint8Array數組時,需要使用String.fromCharCode.apply()方法來將數組中的元素轉換為一個字元串。
五、總結
本文介紹了在JavaScript中將字元串轉換為Base64編碼的方法,以及一些常用技巧,包括封裝函數、處理Unicode字元和處理二進位數據。掌握這些技巧可以在實際開發中更方便地進行數據傳輸和存儲。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/280848.html