Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
¿Cómo puedo mostrar solo los primeros x caracteres de un código HTML que cuenta sin etiquetas?

Uso un editor de texto que generará un código html y guardo en la base de datos ese código html. En otra página, solo quiero mostrar los primeros 100 caracteres, pero no quiero contar las etiquetas html.

Por ejemplo, tengo este código html guardado en db:

 <p><span style="color:red; font-size:20px; font-family:Arial"> Here is the real text that I want to strip to 100 characters</span></p> <p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>

Si hago una subcadena como de costumbre en javascript, producirá algo como esto:

 <p><span style="color:red; font-size:20px; font-family:Arial"> Here is the real text that I want to s

Y esto también rompió el código html.

Lo que quiero es tener así:

 <p><span style="color:red; font-size:20px; font-family:Arial"> Here is the real text that I want to strip to 100 characters</span></p> <p>Can be splited <b>between</b> multiple divs. H<p>

Estoy usando angular 4 para este proyecto. Entonces, cualquier idea que use JS, angular, CSS, HTML o en el backend que tengo node.js será útil.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

En la interfaz, puedes hacer algo así:

 var div=document.createElement("div"); div.innerHTML='<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>'; var excerpt=div.innerText.substring(0,100); console.log(excerpt)

Donde excerpt son los 100 primeros caracteres.

Edite si desea mantener las etiquetas html, verifique esto:

 var count = 0; function strip(el, max) { var children = Array.prototype.slice.call(el.childNodes); children.forEach((node) => { if (node instanceof Text) { var newCount = count + node.textContent.length; var diff = newCount - max; if (diff > 0) node.textContent = node.textContent.substring(0, node.textContent.length - diff); count += node.textContent.length; } else if (node instanceof HTMLElement) { if (count >= max) node.remove(); // remove unnecessary tags else strip(node, max); // do recursively } }) } var div = document.createElement("div"); div.innerHTML = '<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>' var clone = div.cloneNode(true) strip(clone, 100) document.write("<h2>Original</h2>"); document.write(div.innerHTML); document.write("<h2>Stripped</h2>"); document.write(clone.innerHTML);

Tenga en cuenta que la función de eliminación modificará un HTMLElement existente strip por eso lo cloné.

Si desea hacer esto en el lado del servidor, puede usar un analizador dom para nodejs y usar el mismo enfoque.

over 4 years ago · Santiago Trujillo Report

0

Puede usar htmlToText en el nodo

 var htmlToText = require('html-to-text'); var htmlText = '<p><span style="color:red; font-size:20px; font- family:Arial">Here is the real text that I want to strip to 100 characters</span></p> <p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>'; var text_100firstNonHtml = htmlToText.fromString(htmlText, { wordwrap: 130 }).substring(0,100); console.log(text_100firstNonHtml);
over 4 years ago · Santiago Trujillo Report

0

Usted dice que su backend es nodejs, por lo que lo mejor y más fácil podría ser eliminar todas las etiquetas html en el lado del servidor y enviar solo el texto al cliente con la longitud deseada. Consulte el paquete npm "striptags" para node. https://www.npmjs.com/package/striptags

O con jQuery es bastante fácil (puede ser del lado del servidor o del cliente) pero puede usar cualquier analizador/marco html

 var htmlStr = '<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters aaaaa bbbbbb cccccc ddddd eeeeee ffff ggggg hhhh iiii jjjj kkk llllll mmmm nnnn</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>'; var $html = $(htmlStr); $html.find('*').each(function(idx, tag) { var shortText = $(tag).text().substring(0,100); $(tag).text(shortText); }); console.log($html.html());
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!