Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep line breaks in HTML string

Using Angular 5 and Firebase, I am storing and retrieving movie review information. When creating and editing the review, line breaks are kept (I assume using an ngModel has something to do with this). However, when retrieving the review from a reader's perspective, the ReviewComponent, the line breaks are not kept. Logging the body still shows the line breaks and using Angular's json pipe shows as text\n\ntext showing where the line breaks should be.

Here is my HTML:

<main role="main" class="container">
  <p style="margin-bottom: 2rem;">{{review.body}}</p>
</main>

I have also tried span and body.

How can I keep these line breaks in the review for the reader?

like image 762
cfoster5 Avatar asked Mar 13 '18 00:03

cfoster5


People also ask

How do you keep a line break in HTML?

Preserve Newlines, Line Breaks, and Whitespace in HTML If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!

How do you put a break in text in HTML?

To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags.


1 Answers

HTML, in general, uses br tags to denote a new line. A plain textarea tag does not use this, it uses whatever the user's system uses to denote a new line. This can vary by operating system.

Your simplest solution is to use CSS

<main role="main" class="container">
  <p style="margin-bottom: 2rem;white-space:pre-wrap;">{{review.body}}</p>
</main>

This will maintain any "white space" formatting, including additional spaces.

If you want to actually replace the newline characters with br tags you can use the following regex

<main role="main" class="container">
  <p style="margin-bottom: 2rem;" [innerHTML]="review.body.replace(/(?:\r\n|\r|\n)/g, '<br>')"></p>
</main>

Edit Thanks to ConnorsFan for the heads up on replace not working with interpolation.

like image 57
Jon P Avatar answered Oct 01 '22 18:10

Jon P