I want to truncate a word to 50 characters but in 50 characters it should not be an HTML tag. Suppose I have the below HTML:
<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>
Then it should count 50 characters including only "This is a test message This is a test message This is a test message"
And after truncating, it should display like below:
<p>This is a test message</p>This is a test message<p>This</p>
This I want to achieve using jQuery.
2
Answers
Here is my quick solution, you may need to adjust the output format, but this is how you can achieve using jQuery.
Console output:
I don’t think you need jQuery for this. A quick solution would be to loop over every character. If the character is inside
<
or>
characters, then add it to the final string. Otherwise, only add it if the count of characters already added that were outside<
or>
s is less than 50:The only pitfall of this is that tags like the
<a>
are still included, however, they are empty. Because the extra tags are empty, they won’t show up and it shouldn’t make a difference.