Search code examples
javascripthtmltextarealine-breaks

How to add line breaks to an HTML textarea


I’m editing a <textarea> with JavaScript. The problem is that when I make line breaks in it, they won’t display. How can I do this?

I’m getting the value to write a function, but it won’t give line breaks.


Solution

  • The problem comes from the fact that line breaks (\n\r?) are not the same as HTML <br/> tags:

    var text = document.forms[0].txt.value;
    text = text.replace(/\r?\n/g, '<br />');
    

    Since many of the comments and my own experience have shown me that this <br> solution is not working as expected, here is an example of how to append a new line to a textarea using '\r\n':

    function log(text) {
        var txtArea;
    
        txtArea = document.getElementById("txtDebug");
        txtArea.value += text + '\r\n';
    }