I have an ASP.NET MVC app that shows news articles and for the main paragraph I have a truncate and HTML tag stripper. e.g. <p><%= item.story.RemoveHTMLTags().Truncate() %></p>
The two functions are from an extension and are as follows:
public static string RemoveHTMLTags(this string text)
{
return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
}
public static string Truncate(this string text)
{
return text.Substring(0, 200) + "...";
}
However when I create a new article say with a story with only 3-4 words it will throw this error: Index and length must refer to a location within the string.
Parameter name: length
What is the problem? Thanks
Change your truncate function to this:
public static string Truncate(this string text)
{
if(text.Length > 200)
{
return text.Substring(0, 200) + "...";
}
else
{
return text;
}
}
A much more useful version would be
public static string Truncate(this string text, int length)
{
if(text.Length > length)
{
return text.Substring(0, length) + "...";
}
else
{
return text;
}
}
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