Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode emojis in JavaScript?

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!

like image 537
sadmansh Avatar asked Jun 18 '19 11:06

sadmansh


People also ask

Is Base64 encoded JavaScript?

In JavaScript, it is possible to use Base64 to encode and decode strings. In this article, you will be introduced to the btoa and atob JavaScript functions that are available in modern web browsers.

How do I encode to Base64?

To base64 encode string you can pipe an echo command into the base64 command-line tool. To ensure no extra, hidden characters are added use the -n flag. Without the -n flag you may capture a hidden characters, like line returns or spaces, which will corrupt your base64 encoding.

What symbols are in Base64?

Base64 only contains A–Z , a–z , 0–9 , + , / and = . So the list of characters not to be used is: all possible characters minus the ones mentioned above. For special purposes . and _ are possible, too.


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

like image 87
David M Avatar answered Oct 19 '22 22:10

David M


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/[email protected]/base64.min.js"></script>
like image 2
Shivaji Mutkule Avatar answered Oct 19 '22 23:10

Shivaji Mutkule