truncToLength method
Truncates the string to the given length, trimming trailing whitespace
that may be exposed by the cut, and appending ellipsis if and only if
the string was actually truncated.
lengthcounts characters as runes (Unicode code points), so a character outside the Basic Multilingual Plane, such as an emoji, counts as one and is never cut in half.- Returns the original string unchanged when it has
<= lengthrunes. - When truncated, the returned core (before
ellipsis) is at mostlengthrunes;ellipsisis appended on top of that budget. lengthmust be>= 0. Negative values throw RangeError.
Examples:
'Hello World'.truncToLength(5, ellipsis: '...'); // 'Hello...'
'Hello World'.truncToLength(6, ellipsis: '...'); // 'Hello...' (trailing space trimmed)
'Hello'.truncToLength(10, ellipsis: '...'); // 'Hello' (no truncation)
''.truncToLength(5, ellipsis: '...'); // '' (no truncation)
'😀😀'.truncToLength(1); // '😀'
Implementation
String truncToLength(int length, {String ellipsis = ''}) {
if (length < 0) {
throw RangeError.range(length, 0, null, 'length');
}
// A string never has more runes than UTF-16 code units, so this skips
// the rune count for strings that are short anyway.
if (this.length <= length) return this;
final allRunes = runes.toList();
if (allRunes.length <= length) return this;
return String.fromCharCodes(allRunes.take(length)).trimRight() + ellipsis;
}