I'm using the Javascript window.atob()
function to decode a base64-encoded string (specifically the base64-encoded content from the GitHub API). Problem is I'm getting ASCII-encoded characters back (like â¢
instead of ™
). How can I properly handle the incoming base64-encoded stream so that it's decoded as utf-8?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
There's a great article on Mozilla's MDN docs that describes exactly this issue:
A note on previous solutions: the MDN article originally suggested using
unescape
andescape
to solve theCharacter Out Of Range
exception problem, but they have since been deprecated. Some other answers here have suggested working around this withdecodeURIComponent
andencodeURIComponent
, this has proven to be unreliable and unpredictable. The most recent update to this answer uses modern JavaScript functions to improve speed and modernize code.If you're trying to save yourself some time, you could also consider using a library:
Encoding UTF8 ⇢ base64
Decoding base64 ⇢ UTF8
The pre-2018 solution (functional, and though likely better support for older browsers, not up to date)
Here is the the current recommendation, direct from MDN, with some additional TypeScript compatibility via @MA-Maddin:
The original solution (deprecated)
This used
escape
andunescape
(which are now deprecated, though this still works in all modern browsers):And one last thing: I first encountered this problem when calling the GitHub API. To get this to work on (Mobile) Safari properly, I actually had to strip all white space from the base64 source before I could even decode the source. Whether or not this is still relevant in 2017, I don't know:
Here is 2018 updated solution as described in the Mozilla Development Resources
TO ENCODE FROM UNICODE TO B64
TO DECODE FROM B64 TO UNICODE