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

159
Visualizações
Limit number of characters inside string containing HTML using Javascript

I have a string that looks like the below. I'd like a function in Javascript that would take such a string as a parameter, and number of real characters (ex: 20), and return the final HTML with the limited characters.

<div>
<p>This is line 1</p>
<p>This is the second line</p>
</div>

So for the above, it should return:

<div>
    <p>This is line 1</p>
    <p>This i</p>
</div>

I understand this may be too complicated to do, but i basically want to take an HTML string and ultimately render it with a specified limit of characters. If there is any other way that would also be good. Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do it with the .substring() Function

const numOfChars = 5 - 1; // Five is the Input you get
const pElem = document.querySelectorAll('p');
pElem[1].innerText = pElem[0].innerText.substring(0,numOfChars);
<div>
<p>This is line 1</p>
<p>This is the second line</p>
</div>

Be sure to subtract 1 from the amount of desired characters, because the substring Function starts counting at 0

about 4 years ago · Juan Pablo Isaza 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