开发者

Javascript: Add Break after each 100 characters

If I w开发者_JAVA百科rite to long text for example this:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

The text is going out of the page, I have an idea to fix it, after every 100 characters I could make a <br /> tag. But I don't know how to do it.

Thanks for any help!


Just use the following CSS property on the element that you wish to force wrapping in:

word-wrap: break-word;

No need for any JavaScript!

If you really want to use JavaScript (for concept; CSS is better for accessibility and ease) then go ahead.

Oh, and another thing, if you're using a font that isn't monospace (but rather, proportional), cutting off at 100 characters could be ineffective. One line could have 100 'i' characters, with the next having another hundred 'm' chars, which are very different in size.

Oh, and another thing, you can't just apply a regex replace on the innerHTML unless it's all text. If there could possibly be other elements there, you must actually loop through the nodes, applying the technique to only text nodes.

Oh, and another thing, don't bother. Too many problems doing it with javascript.


You can try the following code

str = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

len = str.length;
loop = len / 100;
document.write(loop);
document.write('<br>');

for(i=0; i<=loop; i++){
  document.write( str.slice( i*100, (i*100)+100) );
  document.write('<br>');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜