处理html显示

处理html显示,主要是编辑器保存后展示的处理

编码处理-基础
export function decodeHTMLEntities(text) {
  if (!text) return ''

  const entities = {
    ' ': ' ',
    '&': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#39;': "'",
    '&apos;': "'",
    '&copy;': '©',
    '&reg;': '®',
    '&trade;': '™',
    '&hellip;': '…',
    '&mdash;': '—',
    '&ndash;': '–',
    '&lsquo;': '\'',
    '&rsquo;': '\'',
    '&ldquo;': '"',
    '&rdquo;': '"'
  }

  return text.replace(/&[a-zA-Z0-9#]+;/g, function(match) {
    return entities[match] || match
  })
}

图片处理
export function extractImagesFromHtml(html, { placeholder = '[[IMG_{i}]]', remove = true } = {}) {
  const doc = new DOMParser().parseFromString(html || '', 'text/html')
  const images = []
  const nodeList = Array.from(doc.body.querySelectorAll('img'))

  nodeList.forEach((img, i) => {
    const data = {
      index: i,
      src: img.getAttribute('src') || '',
      alt: img.getAttribute('alt') || '',
      title: img.getAttribute('title') || '',
      width: img.getAttribute('width') || '',
      height: img.getAttribute('height') || '',
      style: img.getAttribute('style') || '',
      attrs: Array.from(img.attributes).reduce((m, a) => {
        m[a.name] = a.value
        return m
      }, {})
    }
    images.push(data)

    if (remove) {
      img.remove()
    } else {
      const span = doc.createElement('span')
      span.textContent = placeholder.replace('{i}', i) // [[IMG_0]]
      img.replaceWith(span)
    }
  })

  return { html: doc.body.innerHTML, images }
}
使用
this.text=extractImagesFromHtml(decodeHTMLEntities(html))
<p v-html="text.html"></p>
<div class="html-imgs">
    <el-image v-for="item in text.images" :key="item.index" :src="item.src"  :preview-src-list="[item.src]">
    </el-image>
</div>
posted @ 2025-08-28 10:50  流云君  阅读(11)  评论(0)    收藏  举报