Shorten text without splitting words or breaking html tags

前端 未结 8 1355
粉色の甜心
粉色の甜心 2020-12-28 17:06

I am trying to cut off text after 236 chars without cutting words in half and preserving html tags. This is what I am using right now:

$shortdesc = $_helper-         


        
8条回答
  •  旧时难觅i
    2020-12-28 17:36

    Here is JS solution: trim-html

    The idea is to split HTML string in that way to have an array with elements being html tag(open or closed) or just string.

    var arr = html.replace(//g, ">\n")
                  .replace(/\n\n/g, "\n")
                  .replace(/^\n/g, "")
                  .replace(/\n$/g, "")
                  .split("\n");
    

    Than we can iterate through array and count characters.

提交回复
热议问题