Base64 Encoding a String in Javascript
2 minsIn this article, you’ll learn how to encode a string to Base64 encoded format. Javascript has a built-in function named btoa()
(binary-to-ascii) that you can use to perform Base64 encoding.
Base64 Encoding in Javascript (Works for UTF-8 strings: 8-bit bytes)
The following example shows how to Base64 encode a string using the built-in btoa()
function -
var str = "hello:world!?$*&()'-=@~";
// Encode the String
var encodedString = btoa(str);
console.log(encodedString); // aGVsbG86d29ybGQhPyQqJigpJy09QH4=
The default btoa()
function works well for binary data consisting of 8-bit bytes. However, if the input exceeds the 8-bit byte range (e.g. UTF-16), then it throws a Character Out Of Range
exception.
Here is an example -
var str = "Hello 😊";
// Encode the String
var encodedString = btoa(str);
# Output
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range
Generic Base64 Encoding with support for 16-bit encoded strings
To handle Unicode characters, you need to first escape the string somehow to an array of 8-bit bytes and then use window.btoa()
function to encode to Base64.
Here is one approach:
function base64EncodeUnicode(str) {
// First we escape the string using encodeURIComponent to get the UTF-8 encoding of the characters,
// then we convert the percent encodings into raw bytes, and finally feed it to btoa() function.
utf8Bytes = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
});
return btoa(utf8Bytes);
}
base64EncodeUnicode('Hello 😊') // SGVsbG8g8J+Yig==
Using a Library to perform Base64 encoding safely
You can also use a library to perform Base64 encoding and decoding safely. These libraries support encoding and decoding of Unicode characters -
Also Read: Javascript Base64 Decode Example