Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need to convert plain text to code element

I am making a website to display code for a project, and I need a way to read a text file on the server and for every line, I need it to make the text on that line a code element.

Like this:

Input (Example.txt):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Line 1
Line 2
Line 3
Line 4
Line 5

Output:

<code>Line 1</code>
<code>Line 2</code>
<code>Line 3</code>
<code>Line 4</code>
<code>Line 5</code>

>Solution :

Split the string by a newline, then map through the resulting array and wrap each item inside a code element:

const str = `Line 1
Line 2
Line 3
Line 4
Line 5`

const res = str.split("\n").map(e => `<code>${e}</code>`).join('\n')
console.log(res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading