If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:
HA
based on Jon's suggestion the code that I created:
public static string WrapWords(string text, int maxLength)
{
string[] words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length > maxLength) //long word
{
words[i] = words[i].Insert(maxLength, " ");
//still long ?
words[i]=WrapWords(words[i], maxLength);
}
}
text = string.Join(" ", words);
return (text);
}
I'm surprised that nobody has mentioned one of my favorite solutions to this problem, the <wbr>
(optional line-break) tag. It's fairly well-supported in browsers and essentially tells the browser that it can insert a line-break if it's necessary. There's also the related zero-width space character, ​
with the same meaning.
For the use case mentioned, displaying user comments on a web page, I would assume that there is already some output formatting to prevent injection attacks, etc. So it's simple to add these <wbr>
tags every N
characters in words that are too long, or in links.
This is especially useful when you need control over the format of the output, which CSS doesn't always let you do.