I need to truncate paragraph text that may or may not include HTML tags. I'm looking for the most efficient way to do this with straight jQuery or vanilla javascript. You can see the problem here: http://jsfiddle.net/4BzpY/3/
var text = "This <a href=\"\">is</a> some text with a link";
var shortText = jQuery.trim(title).substring(0, 10).split(" ").slice(0, -1).join(" ") + "...";
alert(shortText );
The truncated text will be in a paragraph element that can dynamically expand to show all content. With that being the case, I don't want to strip HTML tags and then show them only when full expanded. HTML should remain as is in the collapsed and expanded states.
If this is for display on a page, a neater way may be to use CSS. Given the HTML:
<span class="truncated">this is truncated text</span>
and the CSS:
.truncated {
overflow: hidden;
display: block;
width: 50px;
white-space: nowrap;
text-overflow: ellipsis;
}
this will display something similar to:
this is...
You can then use JavaScript to remove the CSS class when required. Sample implementation: http://jsfiddle.net/a8QK4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With