Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
How can I show only first x characters from a HTML code counting without tags

I use a text editor that will generate a html code and I save in database that html code. On another page I want to display first 100 characters only, but I don't want to count the html tags.

For example I have this html code saved in 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>

If I substring as usual in javascript it will produce something like this:

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

And this also broke the html code.

What I want is to have like this:

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

I am using angular 4 for this project. So any idea using JS, angular, CSS, HTML or on the backend I have node.js will be helpfull.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

On the frontend, you can do somethign like that :

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)

Where excerpt are the 100 first characters.

Edit if you want to keep the html tags check this:

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

Note that the strip function will modify an existing HTMLElement, that's why I cloned it.

If you want to do this on the server side, you can use a dom parser for nodejs and use the same approach.

over 4 years ago · Santiago Trujillo Relatório

0

You can use htmlToText in node

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 Relatório

0

You say your backend is nodejs, so the best and easiest could be that if you strip out all the html tags in server side and sending only the text to the client with a desired lenght. Check out the "striptags" npm package for node. https://www.npmjs.com/package/striptags

Or with jQuery it is quite easy (can be either on server or client side) but you can use any html parser/framework

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda