November 6, 2023
Understanding character encoding
The TextEncoder API
This method encodes the string into a
Uint8Array as UTF-8 bytes.
TextEncoder is not available or you need a custom solution, you can manually encode a string.
UTF-16 to bytes
UTF-8 to bytes manually
Converting to UTF-8 manually requires more work because you need to handle multi-byte characters properly.
Handling binary data with ArrayBuffer
Sometimes you need to work with
ArrayBuffer directly, particularly when dealing with binary file formats or network protocols.
Converting string to ArrayBuffer
Converting string to ArrayBuffer with UTF-8
Base64 encoding and byte arrays
When transferring data over a medium that does not support binary, such as JSON, you might want to encode your byte array to Base64.
Handling large or complex strings
For large or complex strings, consider streaming the conversion or handling it in chunks to avoid blocking the main thread.
Streaming with TransformStreams
This approach allows the browser to handle each chunk of the string efficiently without locking up the UI.
How to Truncate Date in MySQL