truncateMiddle method
Truncates a long String
in the middle while retaining the beginning and the end.
maxChars
must be more than 0.
If maxChars
> String.length the same String
is returned without truncation.
Example
String f = 'congratulations';
String truncated = f.truncateMiddle(5); // Returns 'con...ns'
Implementation
String truncateMiddle(int maxChars) {
if (this.isBlank || maxChars <= 0 || maxChars > this.length) {
return this;
}
int leftChars = (maxChars / 2).ceil();
int rightChars = maxChars - leftChars;
return '${this.first(n: leftChars)}...${this.last(n: rightChars)}';
}