I would like to implement a functionality that insert a word-breaking TAG if a word is too long to appear in a single line.
protected string InstertWBRTags(string text, int interval)
{
if (String.IsNullOrEmpty(text) || interval < 1 || text.Length < interval)
{
return text;
}
int pS = 0, pE = 0, tLength = text.Length;
StringBuilder sb = new StringBuilder(tLength * 2);
while (pS < tLength)
{
pE = pS + interval;
if (pE > tLength)
sb.Append(text.Substring(pS));
else
{
sb.Append(text.Substring(pS, pE - pS));
sb.Append("​");//<wbr> not supported by IE 8
}
pS = pE;
}
return sb.ToString();
}
The problem is: What can I do, if the text contains html-encoded special chars?
What can I do to prevent insertion of a TAG inside a ß?
What can I do to count the real string length (that appears in browser)?
A string like ♡♥♡♥ contains only 2 chars (hearts) in browser but its length is 14.
One solution would be to decode the entities into the Unicode characters they represent and work with that. To do that use
System.Net.WebUtility.HtmlDecode()if you’re in .NET 4 orSystem.Web.HttpUtility.HtmlDecode()otherwise.But be aware that not all Unicode character fit in one
char.