Expanding on the explanation provided by Chris, the issue lies in how the browser interprets the text you input as HTML content. White spaces and carriage returns are considered word separators rather than line or paragraph breaks, resulting in multiple white space characters being condensed into a single space. This behavior is elaborated on in the HTML specification.
This behavior differs from how text is handled within a textarea element.
To address this problem, following Chris's advice, one should replace carriage returns in the string with HTML <br>
elements:
let enteredText = document.getElementById("TextArea").value;
let updatedText = enteredText.replace(/\n/g, '<br />');
document.write(updatedText);
It's worth noting that you can directly access the value of the textarea using .value
, instead of .childNodes[0].nodeValue
.
In addition, I echo Chris's caution regarding the use of document.write()
- it may not be the most optimal solution.
Furthermore, for systems other than Windows, it might be necessary to also replace \r
.