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.
- Returns the original string unchanged when its length is
<= length. - When truncated, the returned core (before
ellipsis) is at mostlengthcharacters;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)
Implementation
String truncToLength(int length, {String ellipsis = ''}) {
if (length < 0) {
throw RangeError.range(length, 0, null, 'length');
}
if (this.length <= length) return this;
return substring(0, length).trimRight() + ellipsis;
}