There’s no reason to use JS. You can easily tell the browser how to handle newline using the white-space CSS property:
white-space: pre-line;
pre-line
Sequences of whitespace are collapsed. Lines are broken at
newline characters, at<br>
, and as necessary to fill line boxes.
Check out this demo:
<style>
#p_wrap {
white-space: pre-line;
}
</style>
<textarea id="textarea"></textarea>
<p id="p_standard"></p>
<hr>
<p id="p_wrap"></p>
<script>
textarea.addEventListener('keypress', function(e) {
p_standard.textContent = e.target.value
p_wrap.textContent = e.target.value
})
</script>