Skip to content

Instantly share code, notes, and snippets.

@aneves
Last active September 26, 2023 22:00
Show Gist options
  • Save aneves/4250125 to your computer and use it in GitHub Desktop.
Save aneves/4250125 to your computer and use it in GitHub Desktop.
Extension method to add ellipsis at the end of a string if it is too big.
private const string EllipsisString = "…";
public static string Ellipsis(this string str, int maxChars, bool breakOnNewLine = false) {
if (maxChars < 1) {
throw new ArgumentOutOfRangeException(nameof(maxChars), "maxChars must be 1 or more.");
}
string changed = str;
if (breakOnNewLine) {
int newLine = changed.IndexOf('\n');
if (newLine > -1) {
changed = changed.Substring(0, newLine) + EllipsisString;
}
}
if (changed.Length > maxChars) {
int lastWordBoundaryInRange = changed.LastIndexOf(' ', maxChars) - 1;
if (lastWordBoundaryInRange < 0) {
lastWordBoundaryInRange = maxChars -1;
}
changed = changed.Substring(0, lastWordBoundaryInRange);
changed = changed.TrimEnd() + EllipsisString;
}
return changed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment