Javascript為我們提供了一個簡單的方法來實現字符串的Base64編碼和解碼,分別是window.btoa()函數和window.atob()函數。
1 var encodedStr = window.btoa(“Hello world”); //字符串編碼 2 var decodedStr = window.atob(encodedStr); //字符串解碼

看下面的實例代碼:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Javascript中Base64編碼解碼的使用實例 :: http://www.uncletoo.com</title> 5 <style> 6 #result{ 7 height: 200px; 8 width: 500px; 9 overflow-y: auto; 10 border: #ccc dotted 1px; 11 } 12 </style> 13 </head> 14 <body> 15 結果: 16 <div id="result"> </div> 17 <table> 18 <tr><td>輸入要編碼的字符串: </td><td><input type='text' id='estr' value=''></td><td> <button onclick="encodeStr()">編碼</button></td></tr> 19 <tr><td>輸入要解碼的字符串: </td><td><textarea id="dstr"></textarea></td><td> <button onclick="decodeStr()">解碼</button></td></tr> 20 </table> 21 <script> 22 function encodeStr() 23 { // 字符串編碼 24 var str_val = document.getElementById("estr").value; 25 if (str_val === '') 26 { 27 alert("Please Enter string to encode"); 28 } else { 29 var enc = window.btoa(str_val); 30 document.getElementById("result").innerHTML = enc; 31 } 32 } 33 function decodeStr() 34 { // 字符串解碼 35 var str_val = document.getElementById("dstr").value; 36 if (str_val === '') 37 { 38 alert("Please Enter string to Decode"); 39 } else { 40 var dec = window.atob(str_val); 41 document.getElementById("result").innerHTML = dec; 42 } 43 } 44 </script> 45 </body> 46 </html>
