Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more
AI OnAI Off
Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more
I'm using the StripPreviewText-function from the Public Templates to show a preview of a number of articles, however it sometimes crash on the row previewText = previewText.Substring(0, previousWord); and at these moments the previousWord is -1. Any ideas of what could cause the problem? I'm not sure what the row before the if, setting the value of previousWord, does.
/// <summary>
/// Strips a text to a given length without splitting the last word.
/// </summary>
/// <param name="previewText">The string to shorten</param>
/// <returns>A shortened version of the given string</returns>
private static string StripPreviewText(string previewText, int maxLength)
{
if (previewText.Length <= maxLength)
{
return previewText;
}
previewText = previewText.Substring(0, maxLength);
// The maximum number of characters to cut from the end of the string.
int maxCharCut = (previewText.Length > 15 ? 15 : previewText.Length - 1);
int previousWord = previewText.LastIndexOfAny(new char[] { ' ', '.', ',', '!', '?' }, previewText.Length - 1, maxCharCut);
if (previousWord <= 0)
{
previewText = previewText.Substring(0, previousWord);
}
return previewText + " ...";
}