You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中通过方法实现选择性转义:保留 转义其余HTML

Vue 中保留指定 HTML 字符(如 )并转义其余内容的实现方法

核心结论

Vue 没有内置支持「保留部分HTML字符、转义其余内容」的方法,需要自行编写自定义转义逻辑来实现需求。

Vue 默认转义/解析逻辑说明

  • 使用{{ text }}插值时,Vue 会调用内部的全量转义函数,将所有HTML特殊字符(包括&、<、>等)转换为对应的实体字符,所以&nbsp;会被转义成&amp;nbsp;,<strong>会被转义成&lt;strong&gt;。
  • 使用v-html指令时,Vue 会直接将内容作为原始HTML插入DOM,不做任何转义,因此所有HTML标签和实体都会被浏览器解析渲染。

自定义实现方案

1. 通用HTML转义函数

首先实现一个标准的HTML转义函数,用于转义除指定字符外的所有HTML特殊字符:

escapeHtml(str) {
  const escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return str.replace(/[&<>"']/g, match => escapeMap[match]);
}

2. 针对目标文本的格式化处理

针对你提供的文本&nbsp;&nbsp;<strong>something</strong>,可以通过两种方式处理:

方式一:拆分文本保留开头的 

适合仅开头存在&nbsp;的场景:

<p v-html="formatText(text)"></p>
<script>
export default {
  data() {
    return {
      text: "&nbsp;&nbsp;<strong>something</strong>"
    }
  },
  methods: {
    escapeHtml(str) {
      const escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      };
      return str.replace(/[&<>"']/g, match => escapeMap[match]);
    },
    formatText(rawText) {
      // 匹配开头连续的&nbsp;
      const nbspMatch = rawText.match(/^(&nbsp;)+/);
      // 提取需要保留的&nbsp;部分
      const preservedNbsp = nbspMatch ? nbspMatch[0] : '';
      // 提取剩余需要转义的文本
      const restContent = rawText.replace(/^(&nbsp;)+/, '');
      // 拼接结果:保留的&nbsp; + 转义后的内容
      return preservedNbsp + this.escapeHtml(restContent);
    }
  }
}
</script>

方式二:全局替换保留任意位置的 

适合文本中任意位置存在&nbsp;的场景:

<p v-html="formatText(text)"></p>
<script>
export default {
  data() {
    return {
      text: "&nbsp;&nbsp;<strong>something</strong>&nbsp;end"
    }
  },
  methods: {
    escapeHtml(str) {
      const escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      };
      return str.replace(/[&<>"']/g, match => escapeMap[match]);
    },
    formatText(rawText) {
      // 用临时标记替换所有&nbsp;,避免转义
      const tempMarker = '__TEMP_NBSP__';
      const tempText = rawText.replace(/&nbsp;/g, tempMarker);
      // 转义整个文本
      const escapedText = this.escapeHtml(tempText);
      // 将临时标记替换回&nbsp;
      return escapedText.replace(new RegExp(tempMarker, 'g'), '&nbsp;');
    }
  }
}
</script>

以上两种方式最终都会输出:&nbsp;&nbsp;&lt;strong&gt;something&lt;/strong&gt;(浏览器渲染后显示为两个空格加纯文本<strong>something</strong>),符合你保留&nbsp;、转义其余HTML的需求。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:25:18