我有一个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) + "...";
}
Run Code Online (Sandbox Code Playgroud)
然而,当我创建一篇新文章说一个只有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;
}
}
Run Code Online (Sandbox Code Playgroud)
一个更有用的版本
public static string Truncate(this string text, int length)
{
if(text.Length > length)
{
return text.Substring(0, length) + "...";
}
else
{
return text;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4812 次 |
| 最近记录: |