Handling linebreaks in JSON

What is the best way to handle linebreaks from JSON?
When saving data from a TextArea to JSON, the linebreaks are \n
When rendered back in html, the linebreaks do not work.
Using <pre></pre> tags makes it work but removes formatting.

<pre>{{sometextdata}}</pre>

I could add fonts to the <pre> in scss but this seems like it may not be the best/easiest way to handle this.
Any Ionic2 options?

If using the <pre> tags are the way to go - what is the default font ionic2 uses so I can push this back to the <pre> tags?

you should replace the newlines with html breaks

value.replace(/\\n/g, '<br \/>')

Something like this (this is untested)

if you have something like that:

{{textWithLineBreaks}}
your text should be fine

if your are doing something like that: value.replace(/\\n/g, '<br>')

you should see the <br> as string printed to your website.
if you want to render the html:
<div [innerHtml]="valueWithTags"></div>

Btw: if you are using html4 or 5 you do not need to mark the br as self-closed … it is only necessary in xhtml

that’s a bad habit of mine. Hard to get rid of :slight_smile:

{{textWithLineBreaks}} does not produce the linebreak.

Here is an example of the text saved in JSON from a TextArea:
{“description”:“One Two Three\nFour Five Six”}

Note the \n

When I used the following: textWithLineBreaks = textWithLineBreaks.replace(/\\n/g, '<br \/>')
It does not work.
However this does:
textWithLineBreaks = textWithLineBreaks .replace(/\n/g, '<br \/>')

This does do as you mention though - display the <br />
So I used the <div [innerHtml]="test2"></div>

So while this ultimately works, it seems that there must be a better way.
Maybe the way I am saving the JSON from the TextArea?

1 Like

I am now using value.replace(/\\n/g, '<br \/>'); when saving the JSON.
Oddly the double slash works here but not when rendering the text.

Still not sure if this is the best way to go - but is working.
If there is a better solution for handling linebreaks saved in JSON from a TextArea …