How To Encode and Decode Strings with Base64 in JavaScript

In JavaScript, you can use the btoa() function to encode a string to Base64 and atob() function to decode a Base64-encoded string back to its original form. Here's a simple example:

Encoding (String to Base64):

        
            const originalString = 'Hello, World!';

            // Encoding to Base64
            const base64EncodedString = btoa(originalString);
            
            console.log('Original String:', originalString);
            console.log('Base64 Encoded String:', base64EncodedString);            
        
    

Decoding (Base64 to String):

        
            const base64EncodedString = 'SGVsbG8sIFdvcmxkIQ==';

            // Decoding from Base64
            const decodedString = atob(base64EncodedString);
            
            console.log('Base64 Encoded String:', base64EncodedString);
            console.log('Decoded String:', decodedString);            
        
    

Remember that the btoa() and atob() functions work with ASCII strings. If you try to encode non-ASCII characters, you might encounter issues. In that case, you may need to use btoa(unescape(encodeURIComponent(originalString))) for encoding and decodeURIComponent(escape(atob(base64EncodedString))) for decoding to handle non-ASCII characters correctly.

Here's an example that handles non-ASCII characters:

Encoding and Decoding with Non-ASCII Characters:

        
            const originalString = '你好,世界!';

            // Encoding to Base64 with non-ASCII characters
            const base64EncodedString = btoa(unescape(encodeURIComponent(originalString)));
            
            console.log('Original String:', originalString);
            console.log('Base64 Encoded String:', base64EncodedString);
            
            // Decoding from Base64 with non-ASCII characters
            const decodedString = decodeURIComponent(escape(atob(base64EncodedString)));
            
            console.log('Base64 Encoded String:', base64EncodedString);
            console.log('Decoded String:', decodedString);            
        
    

Always ensure that you handle encoding and decoding consistently, especially when dealing with special characters or when interoperating with other systems that might expect a specific format.

SSH Essentials: Working with SSH Servers, Clients, and Keys

SSH (Secure Shell) is a cryptographic network protocol that allows secure communication between two computers over an insecure network. It is commonly used for remote login and command execution but can also be used for secure file transfer and other …

read more

How To Set Up an Ubuntu Server on a DigitalOcean Droplet

Setting up an Ubuntu Server on a DigitalOcean Droplet is a common task for deploying web applications, hosting websites, running databases, and more. Here's a detailed guide to help you through the process. Setting up an Ubuntu server on a DigitalOce …

read more