wangEditor icon indicating copy to clipboard operation
wangEditor copied to clipboard

组件升级时兼容旧数据

Open liyangyangi opened this issue 1 year ago • 1 comments

问题描述

之前都是用的 xheditor插件,比较组件比较老样式不好看升级成 wangEditor

请输入遇到的问题... 旧数据不能正常回显

wangEditor 版本

"@wangeditor/editor": "^5.1.23",
"@wangeditor/editor-for-vue": "^5.1.12"

发现是外层没有p标签导致,还有一些旧数据有空标签,比如:
'<strong><span style="color:#ff0000;">注册新会员送腾讯视频VIP周卡</span></strong>限定兑换礼品<br /><br />周末早午餐三人同行一人免单券一张<br /><br />本券仅限餐厅使用<br />可享受周末半自助午餐成人全价票三人同行一人免单<br /><br /><blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;"></blockquote><p>*不与其他优惠同享,不兑现,不找零,赠送一人免单部分不开具发票</p><blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;"></blockquote><p>*无需预约,消费高峰期可能需要等位</p><blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;"></blockquote><p>*仅限堂食,不提供外带</p>*使用时间:<strong>周六至周日12:00-14:30</strong><br /><p>活动详情请洽询店员;</p><p></p>'

liyangyangi avatar Nov 21 '24 07:11 liyangyangi

解决方案是格式化一下旧数据,基本能正常回显。

// 格式化旧数据
//移除空标签
function removeEmptyTags(html) {
  // 匹配任何没有内容的标签
  const regex = /<([a-z][a-z0-9]*)\b[^>]*>([\s\n\r\t]|&nbsp;)*<\/\1>/gi
  // 使用 replace 方法和正则表达式来替换匹配到的空标签为空字符串
  let cleanHtml = html.replace(regex, '')
  // 由于可能存在嵌套的空标签,需要循环处理直到所有空标签都被移除
  while (regex.test(cleanHtml)) {
    cleanHtml = cleanHtml.replace(regex, '')
  }
  return cleanHtml
}
//外层没有p标签包裹的内容加上p标签
function wrapInParagraph(str) {
  // 使用正则表达式找到所有未被 <p> 标签包裹的文本块
  return str.replace(/(^|<\/p>)([\s\S]*?)(<p>|$)/g, function (match, before, text, after) {
    // 如果匹配的文本不是空的,并且不以 <p> 开头也不以 </p> 结尾,则包裹 <p> 标签
    if (text.trim() !== '' && !text.startsWith('<p>') && !text.endsWith('</p>')) {
      return before + '<p>' + text.trim() + '</p>' + after
    }
    return before + text + after
  })
}
function preprocessData(html) {
  //移除空标签
  html = removeEmptyTags(html)
  //外层没有p标签包裹的内容加上p标签
  html = wrapInParagraph(html)
  return `${html}`
}

liyangyangi avatar Nov 21 '24 07:11 liyangyangi