How to base64 encode emojis in JavaScript?

Viewed 8592

I've been trying to encode a twitter embed code into base64 that may or may not contain one or multiple emojis. So when there is an emoji in the string, I get this error: Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Is there anything I can do so that when I run btoa() on my string, it encodes the whole string including the emoji, and when I decode it using base64_decode in php, the emoji appears again?

Thanks in advance!

2 Answers

You can encode it by escaping it first and then calling EncodeUriComponent on it.

This looks like this:

btoa(unescape(encodeURIComponent('')));

The emoji above would return "8J+Ygg=="

To decode it you would do this

decodeURIComponent(escape(window.atob('8J+Ygg==')));

You could make two functions that make this a bit easier:

//Encode
function utoa(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
//Decode
function atou(str) {
    return decodeURIComponent(escape(window.atob(str)));
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa

Use js-base64 library as

var str = "I was funny ";
console.log("Original string:", str);

var encodedStr = Base64.encode(str)
console.log("Encoded string:", encodedStr);

var decodedStr = Base64.decode(encodedStr)
console.log("Decoded string:", decodedStr);
<script src="https://cdn.jsdelivr.net/npm/js-base64@2.5.2/base64.min.js"></script>

Related