Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 641
bjork24 Avatar asked Jan 13 '23 00:01

bjork24


1 Answers

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/

like image 153
Adrian Wragg Avatar answered Jan 16 '23 00:01

Adrian Wragg