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!
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.
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.
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.
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/[email protected]/base64.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With