Text to HTML conversion in Node Js

9.7k Views Asked by At

I am using nodemailer to send mail from node server. I am getting the content for this mail from MSSQL SQL server which is formatted in plain text format, which meansa there are new line characters in it, however when I send it using nodemailer the newline characters are missing and the whole text looks messed up. The other way is to insert html tags for line break in the plain text and send this works fine. But there is too much mannual work involved what I am looking is for a library or utility which can convert the plain text into the html which I can send using mail.

Is there any liberary for this requirement or a way to do this automatically?

3

There are 3 best solutions below

0
On BEST ANSWER

The following will wrap all parts that are separated by more than one newline in paragraphs (<p>...</p>) and insert breaks (<br>) where there is just one newline. A text block without any newlines will simply be wrapped in a paragraph.

template = '<p>' + template.replace(/\n{2,}/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';

So for example, it will take this:

Title

First line.
Second line.

Footer

And convert it to this:

<p>Title</p><p>First line.<br>Second line.</p><p>Footer</p>
1
On

The simplest solution is you can replace the new line characters with <br>.

Try

text.split('\n').join('\n<br>\n')

then you are done.

3
On

Ok finally this code snippet worked for me -

template = template.replace(/\n/gi, "</p></br/>")
template = template.replace(/<\/p>/gi, "</p><p></br/>")

This was a lot of hit and trial but eventually it worked.