5

I am trying to pass a HTML <textarea> through JavaScript, and want to keep the line breaks. Ex when I write:

Line a
Line b

It comes out as:

Line a Line b

My code:

function textwrite(){
  thetext = document.getElementById("text_change").value;    
  document.getElementById("demo").innerHTML = thetext;
}
<textarea id='text_change' oninput='textwrite()'></textarea>
    
<p id="demo"></p>

And I don't want to use <pre> tag.

Mamun
  • 66,969
  • 9
  • 47
  • 59
user2868139
  • 97
  • 2
  • 6
  • 1
    Possible duplicate of [JavaScript: How to add line breaks to an HTML textarea?](https://stackoverflow.com/questions/863779/javascript-how-to-add-line-breaks-to-an-html-textarea) – mrgrechkinn Oct 25 '18 at 14:03
  • Possible duplicate of [Preserve line breaks in textarea](https://stackoverflow.com/questions/30593103/preserve-line-breaks-in-textarea) – BambiOurLord Oct 25 '18 at 14:06

3 Answers3

6

Use white-space:

The white-space CSS property sets how white space inside an element is handled.

with value pre-wrap where

Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

function textwrite(){
  thetext = document.getElementById("text_change").value;    
  document.getElementById("demo").innerHTML = thetext;
}
#demo { white-space: pre-wrap; }
<textarea id='text_change' oninput='textwrite()'></textarea>
    
<p id="demo"></p>
Mamun
  • 66,969
  • 9
  • 47
  • 59
4

Replace \n,\r,\n\r with </br> in java script:

var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

function textwrite(){
     thetext = document.getElementById("text_change").value;  
      var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

     document.getElementById("demo").innerHTML = myLineBreak;
    }
<textarea id='text_change' oninput='textwrite()'></textarea>
    
    <p id="demo"></p>
NullPointer
  • 7,094
  • 5
  • 27
  • 41
0

To do that, first set the multiline property of the textBox to true and then include at the end of each line this: "\r\n"

Paplusc
  • 1,080
  • 1
  • 12
  • 24