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

129
Visualizações
Javascript - How to count character for each line of a div

I am designing my website and am struggling with typography. I would like to realize how many characters there are in each line of my paragraph div. Is there any way to do this with Javascript or jQuery?

For example: I have a 720px wide div with an 18px font size, how can I count how many characters there are for each line? If this is feasible I would also like to understand how to count the spaces or exclude them from the count.

I am currently using $("#mydiv p").text().length but it counts all characters and not characters for each line.

I appreciate any help and thank you for any replies.

document.write( $("#mydiv p").text().length );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="mydiv" style="font-size: 18px; width: 720px; border: 1px solid red;">
<p>This is my div! This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!</p>
</div>

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

0

If you just need to set a character per line limit just use the ch unit like so:

.max720{
  width:720px;
  font-size:18px;
}

.max50ch p{
max-width:50ch;
}
<div class="max720 max50ch">
  <p><strong>Max 50 characters per line.</strong> One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p>

<p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p>
  </div>

Example 2: count characters per line

If you need to get the exact characters per line count, you'll need to to split your text content to an array of characters and and check the line's offsetHeight.

let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(function (paragraph, p) {
  let text = paragraph.textContent;
  //split to character array
  let textArr = text.split("");
  //append temporary span element
  let line = document.createElement("span");
  paragraph.insertBefore(line, paragraph.firstChild);
  let charCount = 0;
  let charArr = [];
  let lineNo = 1;
  let lineY = line.offsetHeight;

  textArr.forEach(function (char, i) {
   //add text character by character
    line.textContent += char;
    charCount++;
    let currentY = line.offsetHeight;
    //currentY > lineY = new line
    if (currentY > lineY || i == textArr.length - 1) {
      let charPerLine = charCount - 1;
      console.log(`paragraph ${p+1};  line ${lineNo}: ${charPerLine} characters`);
      lineY = currentY;
      charCount = 0;
      lineNo++;
    }
  });
  //remove span
  line.remove();
});
.max720{
  width:720px;
  font-size:18px;
}
<div class="max720 max72ch">
  <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p>

<p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p>
  </div>

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