What's the quickest way to truncate paragraph text that may or may not include HTML elements?

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/


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.


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/


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.