Home > Article > Web Front-end > How to Decode UTF-8 Strings from Base64 in JavaScript?
Using JavaScript's atob to decode base64 doesn't properly decode utf-8 strings
JavaScript's atob() function decodes base64-encoded strings, but it assumes that the input is ASCII-encoded. This can lead to problems when decoding strings that contain non-ASCII characters, such as those encoded in UTF-8.
The solution to this problem is to use a function that specifically decodes UTF-8 strings. One such function is decodeURIComponent(), which can be used to decode a UTF-8 string that has been encoded with encodeURIComponent().
<code class="javascript">const decodedString = decodeURIComponent(encodedString);</code>
Another option is to use a library such as [js-base64](https://www.npmjs.com/package/js-base64) or [base64-js](https://github.com/beatgammit/base64-js), which provide functions for encoding and decoding base64 strings.
Here is an example of how to use js-base64 to decode a UTF-8 string:
<code class="javascript">const decodedString = Base64.decode(encodedString);</code>
Once you have decoded the string, you can use it as a regular JavaScript string.
The above is the detailed content of How to Decode UTF-8 Strings from Base64 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!