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?
You could do something like this:
String truncateWithEllipsis(int cutoff, String myString) {
return (myString.length <= cutoff)
? myString
: '${myString.substring(0, cutoff)}...';
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With