Last active
September 26, 2023 22:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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