truncate method

String truncate(
  1. int length
)

Truncates the String when more than length characters exist.

length must be more than 0.

If length > String.length the same String is returned without truncation.

Example

String f = 'congratulations';
String truncated = f.truncate(3); // Returns 'con...'

Implementation

String truncate(int length) {
  if (this.isBlank || length <= 0 || length >= this.length) {
    return this;
  }

  return '${this.substring(0, length)}...';
}