In javascript, how can I obtain the same result of the function Uint8Array.fromBase64() in a browser that doesn't support this function? Can you write me an example?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To achieve the same result as Uint8Array.fromBase64() in browsers that do not support this function, you can use a combination of the built-in atob() function and Uint8Array. The atob() function decodes a base64 string into a binary string, and then you can convert each character of that string into its corresponding byte value to create a Uint8Array.
Here is a concise and widely compatible example:
javascript
function uint8ArrayFromBase64(base64) {
// Decode base64 to binary string
const binaryString = atob(base64);
// Create a Uint8Array and fill it with char codes from the binary string
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
// Example usage:
const base64 = "SGVsbG8gV29ybGQ="; // "Hello World"
const uint8 = uint8ArrayFromBase64(base64);
console.log(uint8); // Uint8Array(11) [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
This approach works in all modern browsers and even in older ones like Internet Explorer, as long as atob() is available[4].
One-liner alternative:
If you prefer a more compact version and don't need to support extremely large base64 strings, you can use:
javascript
const uint8 = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
This is functionally equivalent and especially convenient for short or moderate-length base64 strings[4].
Note:
This method assumes the base64 string uses the standard alphabet (A–Z, a–z, 0–9, +, /) and may include padding (=).
If you need to handle base64url (with - and _), replace those characters before decoding.
This polyfill provides the same output as Uint8Array.fromBase64() for standard use cases in browsers that lack native support[2][4].