0

I want to render a block of text exactly as it's written into an HTML element. So if there are multiple consecutive spaces, I want to render all the spaces, rather than truncating them to a single space, as is the default. I cannot simply replace the spaces with  , as that would, ahem, not break lines. I still want line breaks to occur naturally. How would I go about doing this in JavaScript?

text.replace(/ /g, " ") - doesn't break lines.

I also tried: text.replace(/ /g, " "), which gave the same result as the default behavior - truncating multiple spaces into a single space.

3
  • 3
    Would the white-space: pre; css rule be relevant to your usage? Not quite what you asked for, but could be what you need. Commented Oct 25, 2018 at 5:29
  • @Shadow: pre would not break lines; what OP wants is pre-wrap. Commented Oct 25, 2018 at 5:30
  • @Amadan - yeah, that's what I meant. Commented Oct 25, 2018 at 5:38

1 Answer 1

4

The correct tool here is not JavaScript, but CSS (specifically, white-space property value pre-wrap:

.no-collapse {
  white-space: pre-wrap;
}
<div class="no-collapse">
Lorem ipsum         dolor sit amet,    consectetur adipiscing elit.
            Nunc pellentesque felis id elementum         maximus.
Cras       facilisis dui         felis, ut tincidunt ante            sagittis ut.                  Ut pulvinar      tortor eu      massa porta,       sagittis maximus nisl       viverra.      Donec vel luctus          est.         Integer           semper commodo tortor,               quis elementum     ex fringilla vitae.   Aliquam erat volutpat.         Vestibulum   quis   risus   elementum,          ornare nulla non,   scelerisque lorem.

Nam
 at
  ante
   porttitor,
    tempus
     tellus
      quis,
       lacinia
        velit.
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.