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

后端 未结 3 1247
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 14:14

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 14:52

    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 = $('
    ').html(text).text();

    This is 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/

提交回复
热议问题