Convert to base64 an object with string with proper escaping
Posted on October 8, 2021
Let's suppose I have this object:
const json = {a: true, b: 1, c: 'Some string with <b>HTML</b> andπ»'}
And I'd like to safetly pass without break it.
So, I'm convert it as string:
const str = JSON.stringify(json)
And escaping it:
const esc = unescape(encodeURIComponent(str))
And convert it as Base64:
const base = btoa(esc)
Here the back conversion that works as expected:
decodeURIComponent(escape(atob(base)))