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):
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)