0

If I write 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!

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • 1
    You will find in reality this doesn't really cause a major problem. Creating a long text string like that is usually only something that you would do in a testing environment. – Andrew Jul 07 '10 at 11:01
  • 1
    dup: http://stackoverflow.com/questions/1772941/how-can-i-insert-a-character-after-every-n-characters-in-javascript – Haim Evgi Jul 07 '10 at 11:01
  • 1
    This is not text. Normal text contains words (letters with spaces) and it breaks by your browser automatically. – GOsha Jul 07 '10 at 11:03
  • 4
    Just to answer your question `str = str.replace(/(.{100})/g, "$1
    ");`
    – Amarghosh Jul 07 '10 at 11:04
  • 1
    without inserting s.replace(/([^\n]{100})/g, '$1\n'); – DomreiRoam Jul 07 '10 at 11:46
  • 1
    @DomreiRoam, unless the element in question has `white-space: pre;` or something similar that allows `\n` to carry through, you'd need a `
    `.
    – Delan Azabani Jul 07 '10 at 11:53

2 Answers2

7

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.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
1

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>');
}
DACrosby
  • 11,116
  • 3
  • 39
  • 51
jimy
  • 4,848
  • 3
  • 35
  • 52