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

158
Views
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 answers
Answer question

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