CaptainStiggz
CaptainStiggz

Reputation: 1897

Replace spaces with breaking spaces in JavaScript

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.

Upvotes: 0

Views: 190

Answers (1)

Amadan
Amadan

Reputation: 198314

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>

Upvotes: 4

Related Questions