MoreLesson 278Free preview
JS String Length
This lesson is part of How To · All levels
Summary
The length property gives the number of code units in a JavaScript string. For ordinary text, the result is equal to the number of characters, but emoji and characters outside BMP can be counted more than one. Use Array.from() or Intl.Segmenter if you need to count the characters the user sees.
Key points
- Str.length returns the number of units of UTF-16 code, not the number of visual characters.
- Spacing and punctuation are counted as characters.
- Emojis like 😀 can have a length of 2 because they're made up of two unit code.
- Array.from(str) .length counts the code point; Intl.Segmenter is more appropriate for the grapheme.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.