Get the length of a string in bytes
Count UTF-8 bytes rather than characters.
function byteLength(text) { return new TextEncoder().encode(text).length; }
Input & expected output
Input
"héllo"Expected output
6The edge case
Input
"😀"Expected output
4Know the limits
- UTF-8 is what most APIs and email bodies use. Email header lines are limited to 998 bytes excluding CRLF (RFC 5322); measure bytes, not characters.
- The original used new Blob([text]).size, which also measures UTF-8.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Get the length of a string in bytes from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses TextEncoder instead of Blob so it runs in workers and Node.js alike. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.