Coder Perfect

How do I add line breaks to a textarea in HTML?


I’m using JavaScript to edit a textarea. The issue is that when I insert line breaks, they do not appear. I’m not sure how I’m going to accomplish it.

I’m getting the data I need to construct a function, but it’s not allowing me to insert line breaks.

Asked by djairo

Solution #1

The issue arises because line breaks (nr?) are not the same as HTML br/> tags.

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


Because many of the comments and my own experience indicate that this br> method does not perform as expected, here is an example of how to append a new line to a textarea using the ‘rn’ command.

function log(text) {
    var txtArea ;

    txtArea = document.getElementById("txtDebug") ;
    txtArea.value +=  text + '\r\n';

Because this is a way too common answer to be incorrect or incomplete, I opted to make this an edit rather than a new question.

Answered by TStamper

Solution #2

If you’re using a standard Java script and need to assign a string to a text area value,


n or br > should be replaced with n.

Otherwise, all browsers return Uncaught SyntaxError: Unexpected token ILLEGAL.

Answered by jit

Solution #3

Perhaps someone will find this useful:

I had a problem with line breaks that were given from a server variable to a javascript variable, which was then written to the textarea by javascript (using knockout.js value bindings).

Double escaping new lines was the solution:

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

Javascript was not parsing with simply single escape chars on the server side.

Answered by 0lukasz0

Solution #4

Inside the textarea, you must use n for linebreaks.

Answered by strubester

Solution #5

The pre> tag can be used to display text within your own page.

Answered by Cristian Tra├Čna

Post is based on