按一定长度截取富文本的文字

2018-11-29  本文已影响0人  good__day

按一定长度截断富文本,以下只做到了截断,没有做到标签闭合。

经搜索发现,浏览器在它们认为合理的位置加入闭合标签。但各浏览器的做法是不同的。

function truncateIgnoreTags(richText, maxLength) {

  const textArr = richText.split(/<\/?\w+[^>]*>/g).filter(Boolean)

  let resTextLength = 0

  const resultRegexp = textArr.reduce((accumulator, cur) => {

    if (resTextLength + cur.length <= maxLength) {

      resTextLength += cur.length

      return accumulator + '[^]*' + cur

    } else {

      if (resTextLength === maxLength) {

        return accumulator

      }

      const curResRegexp =

        accumulator + '[^]*' + cur.substr(0, maxLength - resTextLength)

      resTextLength = maxLength

      return curResRegexp

    }

  }, '')

  const resTextStr = richText.match(new RegExp(resultRegexp))[0]

  return resTextStr

}

上一篇 下一篇

猜你喜欢

热点阅读