Home > Web Front-end > JS Tutorial > body text

How to Decode UTF-8 Strings from Base64 in JavaScript?

Linda Hamilton
Release: 2024-11-01 23:08:29
Original
592 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!