Menu

JavaScript String Length Won’t Enforce a UTF-8 Byte Limit
📰

JavaScript String Length Won’t Enforce a UTF-8 Byte Limit

DEV Community: javascript·Jitsumi·2 days ago
#jnDCKQbG
#devtojavascript#devto#dev#json#bytes
Long article (768 words) — no AI summary yet.
Reading 0:00
15s threshold

An API accepts a 100-byte label. Your JavaScript form allows it because label.length <= 100 . The server rejects a label containing emoji, even though the user typed fewer than 100 visible characters.

Both checks can be behaving correctly while enforcing different units. JavaScript's length counts UTF-16 code units. A UTF-8 byte limit concerns encoded bytes. A character counter for people may need grapheme clusters instead.

Before changing the limit, name the unit. “100 characters” is too vague for an API contract that is enforced in bytes.

Four short strings expose the difference

Save this as string-units.mjs and run node string-units.mjs on a current Node.js release:

import assert from 'node:assert/strict' ;

const encoder = new TextEncoder ( ) ; const cases = [ [ 'A' , 1 , 1 , 1 ] , [ 'é' , 1 , 1 , 2 ] , [ '😀' , 2 , 1 , 4 ] , [ 'e\u0301' , 2 , 2 , 3 ] ] ;

for ( const [ text , units , points , bytes ] of cases ) { assert . equal ( text . length , units ) ; assert . equal ( [ . . . text ] .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.