Wrap the text in div tag!

  • Thread starter Thread starter Santel
  • Start date Start date
S

Santel

Hi, I would like to wrap the text in div tag according to its width.
The text don't have any space. Anyone please suggest me how to do this.
 
Hi there,

Unfortunatelly, HTML related solutions like <wbr/> (not in HTML spec) tag or
word-break css attribute (IE only) are partially working for some browsers
only. But don't worry, there's a generic resolution by inserting an invisible
span inside long words (my example works for plain text with encoded
characters, if you want to break long words in HTML formatted text it's gonna
be harder):

using System.Text.RegularExpressions;
using System;

public static class HtmlUtils
{
public static string BreakLongWords(string input, int maxWordLength)
{
// anonymous method can be used in this case
MatchEvaluator evaluator = delegate(Match match)
{
string text = match.Value;
int length = text.Length;

// this is for html encoded characters that
// are present in the plain text
int startIndex = text.LastIndexOf('&',
length - 1, Math.Min(7, length));

return startIndex != -1 ?
text.Insert(startIndex, WordBreak) :
text + WordBreak;
};

string pattern = string.Format(@"[^\s-]{{{0}}}", maxWordLength);

return Regex.Replace(input, pattern, evaluator);
}

private const string WordBreak =
"<span style=\"font-size:0px;color:transparent;\"> </span>";

}

usage:

<div runat="server" style="width: 200px; border: solid 1px black" id="myDiv">
</div>

and the code behind/beside:
myDiv.InnerHtml = HtmlUtils.BreakLongWords(
"thisIsVeryLongTextWhichWillBeBrokenIntoSmallerPieces", 30);

You should be fine from this point on.

HTH
 
Back
Top