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