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.

8/17/2019 6:54:55 PM

Accepted Answer

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 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.

6/24/2020 12:43:43 AM

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


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.


You need to use \n for linebreaks inside textarea


If you want to display text inside your own page, you can use the <pre> tag.

document.querySelector('textarea').addEventListener('keyup', function() {
  document.querySelector('pre').innerText = this.value;
<textarea placeholder="type text here"></textarea>
<pre style="font-family: inherits">
new lines will
be respected
      and spaces too


I have a textarea with id is #infoartist follow:

<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>

In javascript code, i'll get value of textarea and replace escaping new line (\n\r) by <br /> tag, such as:

var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');

So if you are using jquery (like me):

var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');

Hope it helped you. :-)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]