Coder Perfect

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

Problem

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

UPDATE

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,

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

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 https://stackoverflow.com/questions/863779/how-to-add-line-breaks-to-an-html-textarea