我有一个 ASP.NET MVC 应用程序,用于显示新闻文章,对于主要段落,我有一个截断和 HTML 标签剥离器。例如<p><%= item.story.RemoveHTMLTags().Truncate() %></p>
这两个函数来自扩展,如下所示:
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) + "...";
}
然而,当我创建一篇新文章,说一个只有 3-4 个单词的故事时,它会抛出此错误:Index and length must refer to a location within the string.
Parameter name: length
问题是什么?谢谢
将您的截断函数更改为:
public static string Truncate(this string text)
{
if(text.Length > 200)
{
return text.Substring(0, 200) + "...";
}
else
{
return text;
}
}
一个更有用的版本是
public static string Truncate(this string text, int length)
{
if(text.Length > length)
{
return text.Substring(0, length) + "...";
}
else
{
return text;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)