I've stored a document with a string field in MongoDB Atlas that I use to populate to an HTML (pug) element. I want to indicate a new line in the text using the escape \n. However, the character does not perform the escape and populates the '\n' with the text in HTML, instead of starting a new line of text.
JSON in Mongodb Atlas
{
 "mystring" : "I want this to be two lines. \n Two lines would be great"
}
PUG code:
p!= data.mystring
Renders in HTML as:
I want this to be two lines. \n Two lines would be great
Desired Render in HTML:
I want this to be two lines.
Two lines would be great
FWIW, this worked just fine when I was hosting on MLab. But, we're forced to migrate to Atlas and the same \n escape doesn't seem to work.
In response to your comment that the \n is coming from the database already escaped (\\n), you could use regex within Pug to unescape it:
- let mystring = 'I want this to be two lines. \\n Two lines would be great'
p!= mystring.replace(/\\n/g, '\n')
This will compile to:
<p>I want this to be two lines.
Two lines would be great</p>
However, as you can see in this stack snippet, HTML collapses whitespace characters, so it won't be rendered in multiple lines in a browser.
<p>I want this to be two lines.
Two lines would be great</p>To make the HTML render the line breaks, you need to use a <br> element, as @isAif pointed out.
You could insert this via regex in Pug as well:
- let mystring = 'I want this to be two lines. \\n Two lines would be great'
p!= mystring.replace(/\\n/g, '<br>\n')
This will compile to:
<p>I want this to be two lines.<br>
Two lines would be great</p>
Which will render the line break in browsers, as illustrated below.
<p>I want this to be two lines.<br>
Two lines would be great</p>If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With