If the display involves providing some long url as a link (i.e. <a href=long.url>long.url</a>), you could just keep the full-length string as the href target, and replace as much of the middle as you want with "..." for the display string -- and if you decide to get fancy, use a mouse-over event to display the full-length string as a "tool-tip" style pop-up.
(The point is, people seldom try to actually read a long url -- they usually just glance and click. The careful ones will wait for a pop-up of the full string if they know it will show up, and they can decide to "view source" if it doesn't.)
Of course, if you are not providing an actual <a href=...> link for these critters, well, displaying the whole big string is useful in some sense, though whatever you do to break it up into a bunch of short lines will tend to interfere with any sort of "copy/paste" usage that reader may want to try. Any attempt to select the whole multi-line string will end up with some sort of white-space wherever you inserted a line-break, and this will need to be edited out when someone wants to use it as an actual url.
And if people are sending you really long strings that are not urls, maybe there's some practical need for that, which your current web-page design is not supporting very well, and maybe you should rethink the page layout.
As for the code you tried, I gather it worked (in terms of splitting long words) for the cases you happen to know about. It looks to me like it would work equally well in all cases, in the sense that: if the paragraph string contains any number of substrings with 40 or more non-whitespace characters in a row, a space will be added after the 40th character in the substring. (A string of 80 or more non-whitespace in a row will have two spaces added, and so on.) After applying that operation, the maximum-length non-whitespace string in your paragraph is sure to be 40 characters long.
The other replies above might lead you to a solution that produces more coherent/readable results in a variety of cases, by breaking at strategic points.
In reply to Re: how to find and split long words
by graff
in thread how to find and split long words
by keiusui
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |