1.38.0truncate
Shortens a string to a maximum length and appends an omission string when truncation is required.
truncate(value, length, omission):stringLength validation
The length parameter must be a non-negative integer. Otherwise, truncate throws a RangeError with the message: "truncate: length must be a non-negative integer".
Unicode-aware length
The input and omission are converted with Array.from before their lengths are evaluated or characters are sliced. This means Unicode code points such as surrogate-pair emoji are treated as single characters.
Omission behavior
The default omission is "...". If the omission length is greater than or equal to the requested length, only the first length code points of the omission are returned. Otherwise, the original string is shortened enough to leave room for the complete omission.
Return behavior
If the input already fits within the requested length, the original value is returned. If truncation is required, the returned string consists of the retained portion followed by the omission.
Parameters
valuestringrequiredThe string to truncate.
lengthnumberrequiredThe maximum number of Unicode code points allowed in the result.
omissionstringoptionalThe string appended when the value needs to be truncated.
"..."Returns
stringThe original string when it fits within the requested length, or a truncated string with the omission appended.
Errors
Throws a RangeError if length is not a non-negative integer.
Examples
Basic usage
Long text is shortened and the default omission is appended.
truncate("Hello World", 8);
// "Hello..."Custom omission
A custom omission string can be provided.
truncate("Hello World", 8, "…");
// "Hello W…"Value already fits
If the string length is already within the requested limit, the original value is returned unchanged.
truncate("Hello", 10);
// "Hello"Length shorter than omission
When the omission itself is at least as long as the requested length, only the beginning of the omission is returned.
truncate("Hello World", 2, "...");
// ".."Zero length
A zero length returns an empty string when truncation is required.
truncate("Hello", 0);
// ""Unicode characters
Truncation counts Unicode code points using Array.from.
truncate("Hello 😀 World", 8);
// "Hello 😀..."Empty value
An empty input always returns an empty string.
truncate("", 5);
// ""