Sometimes you need to shorten a long string to certain length without cutting the final word in half and add custom string such as 3 dots to the end, It will moves the pointer up to the previous space, if the limit finished within a word.
Here I listed 3 functions may help you.
Javascript
function Truncate(str, maxLength, suffix)
{
if(str.length > maxLength)
{
str = str.substring(0, maxLength + 1);
str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
str = str + suffix;
}
return str;
}
C#
public static string Truncate(string str, int maxLength, string suffix)
{
if (str.Length > maxLength)
{
str = str.Substring(0, maxLength + 1);
str = str.Substring(0, Math.Min(str.Length, str.LastIndexOf(" ") == -1 ? 0 : str.LastIndexOf(" ")));
str = str + suffix;
}
return str.Trim();
}
public static string Truncate(string str, int maxLength, string suffix)
{
if (str.Length > maxLength)
{
var words = str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var sb = new StringBuilder();
for (int i = 0; sb.ToString().Length + words[i].Length <= maxLength; i++)
{
sb.Append(words[i]);
sb.Append(" ");
}
str = sb.ToString().TrimEnd(' ') + suffix;
}
return str.Trim();
}