Wednesday, 30 September 2015

Base64 encode decode using Javascript



Javascript provides an easy way to Base64 encode and decode a string, using which we can encode decode a string to base64 on the fly.
Two functions window.btoa() & window.atob() can be used to achieve the task.
Example:
var encodedStr = window.btoa(“Hello world”); // to encode a string
var decodedStr = window.atob(encodedStr); // to decode the string
Example :
<html>
    <head>
        
        <style>
            #result{
                height: 200px;
                width: 500px;
                overflow-y: auto;
                border: #ccc dotted 1px;                
            }
        </style>
    </head>
    <body>
Result:
        <div id="result"> </div>
        <table>
            <tr><td>Enter String to Encode: </td><td><input type='text' id='estr' value=''></td><td> <button onclick="encodeStr()">Encode</button></td></tr>
        <tr><td>Enter String to Decode: </td><td><textarea id="dstr"></textarea></td><td> <button onclick="decodeStr()">Decode</button></td></tr>
</table>
        <script>
            function encodeStr()
            { // this will encode the string
                var str_val = document.getElementById("estr").value;
                if (str_val === '')
                {
                    alert("Please Enter string to encode");
                } else {
                    var enc = window.btoa(str_val);
                    document.getElementById("result").innerHTML = enc;
                }
            }
            function decodeStr()
            { // this will decode the string
                var str_val = document.getElementById("dstr").value;
                ;
                if (str_val === '')
                {
                    alert("Please Enter string to Decode");
                } else {
                    var dec = window.atob(str_val);
                    document.getElementById("result").innerHTML = dec;
                }
            }
        </script>
    </body>
</html>

0 comments:

Post a Comment