How to add text in new lines in an ejs file

Viewed 37

Right now I am trying to alter the body of my ejs file with javascript embedded. Here is the code :

<body>
<%- include('navbar.ejs'); %>
  <div class="novel" id="title">
  <p>Novel Title</h3>
</div>
<div id="skip"><button>
    First
  </button>
  <button>
    Last
  </button></div>
<p>
<% for( let index = 0; index < text.length; index++ ) { %>
<%-  text[index] %>
<% } %>

In the for statement, the text variable is a list of a very long string that contains the text of a novel. And every item in the list is separated by the new line so now I want to print it out in the ejs file with each line in a new one.

In this case, it would be like doing

document.write("/n") 

If it were to work on an ejs file.

Thank you in advance.

1 Answers

try testing every character against newline regex, and if true, add a <br>, else the character:

<% for( let index = 0; index < text.length; index++ ) { %>
<%-  (/\r\n|\n|\r/).test(text[index]) ? '<br>' : text[index] %>
<% } %>

or simply split the string by newline, which creates an array which you can join with <br>:

<%-  text.split(/\r\n|\n|\r/).join('<br>') %>

you should escape string by using <%= tags, which will require modifying the code. One option would be to split the string, and then output escaped string along with your HTML newline:

<% const split = text.split(/\r\n|\n|\r/); %>

<% split.forEach(line => { %>

    <%= line %><br>

<% }); %>
Related