Decode URL Safe Base64 in JavaScript (browser side)

21,367

Solution 1

For posterity,

atob(data.replace(/_/g, '/').replace(/-/g, '+'))

As stated by the spec https://www.rfc-editor.org/rfc/rfc4648#section-5 however because this uses atob() it does not support unicode characters and thus requires a polyfill.

Solution 2

Finally found it. This does URL Safe decoding

https://github.com/dankogai/js-base64

Share:
21,367
wibberding
Author by

wibberding

I like the full stack. Ruby (on Rails) and JavaScript are my languages of choice.

Updated on June 14, 2020

Comments

  • wibberding
    wibberding about 4 years

    I am using Gmail's API to get emails from my account. The body of the message is delivered in a "URL safe base64" format. What is the best way to decode this for use? I have found some nodejs solutions, but no client side ones. window.atob does not work since it is URL safe.

    Thanks for any help.

  • moltenform
    moltenform over 6 years
    Was this meant to be atob(data).replace(/_/g, '/').replace(/-/g, '+') instead
  • Tcharl
    Tcharl almost 6 years
    Reading from the Base64 version of common codec, it should be the inverse:btoa(data) .replace(/\//g, '_').replace(/\+/g, '-'))),
  • xori
    xori over 4 years
    jmnben: no we want to replace the '_' and '-' before we do the decoding.