Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: How to Truncate String and add Ellipsis after character number

Tags:

ellipsis

dart

I'd like to add Ellipsis to a string after a certain character length and if the string length is not up to the character preset character length, the ellipsis (...) Should NOT be added.

How do i achieve this in Dart Language?

like image 912
Tayo.dev Avatar asked Nov 18 '18 08:11

Tayo.dev


2 Answers

You could do something like this:

String truncateWithEllipsis(int cutoff, String myString) {
  return (myString.length <= cutoff)
    ? myString
    : '${myString.substring(0, cutoff)}...';
}
like image 194
Nick Avatar answered Sep 26 '22 17:09

Nick


You can use replaceRange method for this.

replaceRange

  var text = 'Hello World!';
  var r = text.replaceRange(7, text.length, '...');
  print(r); // -> Hello W...

Here is a complete example:

String truncate(String text, { length: 7, omission: '...' }) {
  if (length >= text.length) {
    return text;
  }
  return text.replaceRange(length, text.length, omission);
}

void main() {
  print(truncate('Hello, World!', length: 4));
}
like image 35
Murat Ersin Avatar answered Sep 25 '22 17:09

Murat Ersin