Javascript ignores last linebreak with text.(elem.val())

51 views Asked by At

I'm trying to output a textarea value into a pre (or a div with white-space:pre for that matter). All works well, but it skips the last linebreak. So, if you add text and a linebreak, it won't display the linebreak. If you add text and two linebreaks, it displays text and one linebreak. So, it looks like the text is being trimmed. Can anyone suggest why this is happening and how to solve it?

function starter(e) {
  $("#output").text(e);
}

$('#textin').on('input',function(){
  starter($('#textin').val())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textin"></textarea>
<pre id="output" style="border:1px solid black"></pre>

2

There are 2 answers

0
Paul On

I found an answer after reading When are <br> elements ignored when within a paragraph?.

Browsers take a line break not as a line break, but more like 'end of line'.

With that in mind; this semi-dirty trick does the job, adding an extra line break:

function starter(e) {
  $("#output").text(e+'\n');
}
1
Abhinav Srivastava On

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).