Base64 encoding and decoding in client-side Javascript

前端 未结 14 2069
挽巷
挽巷 2020-11-22 04:27

Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding?

14条回答
  •  别跟我提以往
    2020-11-22 05:03

    Modern browsers have built-in javascript functions for Base64 encoding btoa() and decoding atob(). More info about support in older browser versions: https://caniuse.com/?search=atob

    However, be aware that atob and btoa functions work only for ASCII charset. If you need Base64 functions for UTF-8 charset, you can do it with:

    function base64_encode(s) {      
        return btoa(unescape(encodeURIComponent(s)));
    }
    function base64_decode(s) {      
        return decodeURIComponent(escape(atob(s)));
    }
    

提交回复
热议问题