What is string length?

The length of a string depends on what you count. A person sees characters, but programs count code points, UTF-16 code units, or bytes, and these numbers often differ. The emoji ๐Ÿ‘๐Ÿฝ looks like one character, but it is 2 code points, 4 UTF-16 code units, and 8 UTF-8 bytes. JavaScript, Java, and C# report UTF-16 code units as the length, databases often limit bytes, and form fields may count line breaks as two characters.

Tool description

This tool shows the length of a string in four units at once and checks it against a minimum and maximum length. Use it to find out whether a username, title, or database value fits a limit, or why two programs report different lengths for the same text. If the string is too long, you get a truncated copy that fits the limit without cutting a character in half.

Features

  • Counts characters, Unicode code points, UTF-16 code units, and UTF-8 bytes
  • Checks the length against an optional minimum and maximum, in the unit you choose
  • Shows how many units are left, missing, or over the limit
  • Truncates a string that is too long without splitting emoji, flags, or accented letters
  • Can ignore leading and trailing whitespace
  • Can count line breaks as CR LF, the way HTML forms submit them

How it works

Characters are grapheme clusters, the units a person reads as one character, found with the browser's built-in Unicode text segmentation. Code points are the Unicode values in the string. UTF-16 code units are what String.length returns in JavaScript: characters outside the Basic Multilingual Plane, such as most emoji, take two. UTF-8 bytes are the size of the string encoded as UTF-8. Truncation keeps whole characters until the next one would go over the maximum.

Tips

  • For a MySQL VARCHAR or PostgreSQL varchar limit, check by Unicode code points. For a byte limit, such as an index key or a network protocol field, check by UTF-8 bytes.
  • The maxlength attribute of an HTML input counts UTF-16 code units, so an emoji can use up two.
  • Browsers send textarea line breaks as CR LF, so a server that checks length may count each line break twice. Turn on the CR LF option to match.