Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

517
Vistas
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));

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda