通过代码实现截取一定字符的实现

最近,在做毕业设计,有一个需要实现的任务是,用Repeater绑定后台数据,然后再前台进行显示。可是,因为标题过长的缘故,在显示的实话,把包它的div给撑爆了,严重的影响了页面的美观。

故从网上找了些资料,整理如下:

这是前台代码:

<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%#毕业Degin.getSubString.getSubStr(Convert.ToString(Eval("ArticleContent")),234)%>
</ItemTemplate>
</asp:Repeater>
</div>

顺便说一下,上面这种方式获取后台代码,真实太牛了。那天发现了这个秘密之后,大块人心。呵呵!

好了 不废话了,下面是后台代码:

public class getSubString
{
public static string NoHTML(string Htmlstring)
{
if (Htmlstring.IndexOf(@"") > -1)
{
Htmlstring
= HttpContext.Current.Server.HtmlDecode(Htmlstring);
if (Htmlstring.IndexOf(@"&") > -1)
Htmlstring
= HttpContext.Current.Server.HtmlDecode(Htmlstring);
}
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
Htmlstring
= Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
Htmlstring.Replace(
"<", "");
Htmlstring.Replace(
">", "");
Htmlstring.Replace(
"\r\n", "");
Htmlstring
= HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

return Htmlstring;
}

public static string getSubStr(string str, int len)//str是插入的字符串,而len是你需要的长度数
{

string temp = getSubString.NoHTML(str);//去掉特殊的字符。
if (temp.Length > len)
{
return str.Substring(0, len) + "...";//这里,就是网上很多地方,看见一段话后面加上的省略号。
}
else
{
return str;
}
}
}
}
原文地址:https://www.cnblogs.com/damonlan/p/2031067.html