'Pass object to javascript function from ejs

I'm trying to attach a click event from my ejs file but I noticed that when my data coming from my database has a "newline", I get an error that says: Unexpected token in JSON at position 253

app.js

app.get('/', async (req, res) => {
   return res.render('page', {
      data: dataArray
   })
});

page.ejs:

  <% for(let t of data) { %>
  <tr class="tr-<%= t.id %>">
    <td><i class="fas fa-pencil-alt" onclick="editT('<%= JSON.stringify(t) %>')"></i>
    </td>
    <td><%= t.name %></td>
    <td><%= t.description %></td>
  </tr>
  <% } %>

script

function editT(t) {
  t = JSON.parse(t);
  console.log(t)
}

When a description has a "newline" and I use JSON.stringif(t) it comes broken:

let t = '{"id":1,"name":"Lorem","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry!

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
","created_at":"2022-04-18T22:19:00.153Z"}';


console.log(JSON.parse(treatment));


Solution 1:[1]

there two way of doing this without error

first one using <%- %> this way it will write the unescaped string

like this :

<td><i class="fas fa-pencil-alt" onclick="editT('<%- JSON.stringify(t)%>')"></i></td>

second one would be using encode

<td><i class="fas fa-pencil-alt" onclick="editT('<%= encodeURIComponent(JSON.stringify(t))%>')"></i></td>

the second one also requires you to do

function editT(t) {
  t = JSON.parse( decodeURIComponent(t));
  console.log(t)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Divine Soul