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 c
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/
One possibility for this kind of situation is to temporarily convert the data being truncated to text.
Send the HTML to a throwaway element and then extract the text:
var title = $('<div>').html(text).text();
This <a href=\"\">is</a> some text with a link
becomes This is some text with a link
, which can then be truncated safely.
If you need to expand that to the original text again, just keep a copy with the HTML still in it.
Here is an example: http://jsfiddle.net/B2AZA/
I figured it out using regex. Found the example here: https://stackoverflow.com/a/7552371/142486
var text = $('#my-text');
var maxWords = 25;
var words = text.html().match(/<\s*(\w+\b)(?:(?!<\s*\/\s*\1\b)[\s\S])*<\s*\/\s*\1\s*>|\S+/g);
text.html(words.slice(0, maxWords).join(" ") + " ...");
Demo here - http://jsfiddle.net/3Yjm8/
I'll simply add the unadulterated HTML to the element with data()
, then replace it when the box is expanded.