Get the length of a string in bytes

Count UTF-8 bytes rather than characters.

JavaScript Version 1.0.0 · MIT · .md

get-the-length-of-a-string-in-bytes.js
function byteLength(text) { return new TextEncoder().encode(text).length; }

Input & expected output

Input

"héllo"

Expected output

6

The edge case

Input

"😀"

Expected output

4

Know 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.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.