Search code examples
javascripthtmlpreview

Javascript preview box replace \n with <br>


I have a textarea that updates a div below for a preview box. The issue is when u hit enter, in the preview box it should also put an enter. But what it does is 1 time change \n to br then the others just get replaced with a space. I dont generally use javascript so im confuzzled.

My code:

<div class='fl' ><textarea id='textbox' onkeyup="document.getElementById('preview').innerHTML=document.getElementById('textbox').value.replace('\n','<br />');" name='description' class='arial f12' style='width:400px;height:200px;resize:vertical;'></textarea></div>
<div id='preview' class='f12 arial p10' style='background-color:#efefef;'></div>

Example:

1
2
3
4

comes out as:

1
2 3 4

Thanks guys!


Solution

  • Where it says .replace('\n','<br />') use this instead .replace(/\n/g,'<br />')

    The /g means "global" as in "replace all matches". Without it, only the first match gets replaced