JavaScript Reference ยท String
String length property
Reference for the JavaScript string length property: it counts UTF-16 code units, not characters, so emoji and combining marks give surprising results.
The length property of a string holds the number of UTF-16 code units in it. For plain English text that equals the number of characters, which is why "hello".length is 5. For text with emoji, rare scripts or combining accents, the number can be larger than what a reader would count.
It is a data property on each string value, not a method, so you read it without parentheses. An empty string has length 0.
const length = string.length;
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.length
| Part | Description |
|---|---|
| Value | A non-negative integer: the number of 16-bit code units in the string. |
| Attributes | Not writable, not enumerable, not configurable. |
The maximum length of a string depends on the engine; in practice, memory runs out first.
Usage notes
- It counts code units, not characters. Code points above
U+FFFF(most emoji, many historic and rare scripts) are stored as two units called a surrogate pair, so each adds 2. - Three levels of "character". Code units are what
lengthcounts. Code points are what[...string]andfor...ofiterate. Graphemes are what a reader perceives as one symbol; useIntl.Segmenterfor those. - Normalization matters.
"รฉ"can be one code point or two. Callnormalize()before comparing or counting if the input comes from different sources. - Read-only. Assigning to
string.lengthsilently does nothing in sloppy mode and throws aTypeErrorin strict mode (modules and classes are strict). Strings are immutable; build a new string withslice()instead. - Do not confuse with arrays.
array.lengthis writable and truncates the array;string.lengthis not. - Cheap to read. Reading
lengthis constant time; you do not need to cache it in loops. - Slicing by
lengthcan cut a pair in half."๐".slice(0, 1)returns a lone surrogate. Iterate code points or graphemes when you truncate user text. - Limits in forms. The
maxlengthattribute ofinputalso counts UTF-16 code units, so it agrees withstring.length.
Browser support
Supported in every browser and JavaScript engine since the first versions of the language.