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.

How To Open a Port on Linux

Opening a port on Linux involves configuring the firewall to allow traffic through the specified port. Here's a step-by-step guide to achieve this, assuming you are using ufw (Uncomplicated Firewall) or iptables for managing your firewall settings. u …

read more

Troubleshooting Latency Issues on App Platform

Troubleshooting latency issues on an app platform can be complex, involving multiple potential causes across the network, server, application code, and database. Here’s a structured approach to identifying and resolving latency issues. Identify …

read more