How to add line breaks to an HTML textarea? How to add line breaks to an HTML textarea? javascript javascript

How to add line breaks to an HTML textarea?


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 />');

UPDATE

Since many of the comments and my own experience have show 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';}

I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.


if you use general java script and you need to assign string to text area value then

 document.getElementById("textareaid").value='texthere\\\ntexttext'.

you need to replace \n or < br > to \\\n

otherwise it gives Uncaught SyntaxError: Unexpected token ILLEGAL on all browsers.


Maybe someone find this useful:

I had problem with line breaks which were passed from server variable to javascript variable, and then javascript was writing them to textarea (using knockout.js value bindings).

the solution was double escaping new lines:

orginal.Replace("\r\n", "\\r\\n")

on the server side, because with just single escape chars javascript was not parsing.