Vue中通过方法实现选择性转义:保留 转义其余HTML
Vue 中保留指定 HTML 字符(如 )并转义其余内容的实现方法
核心结论
Vue 没有内置支持「保留部分HTML字符、转义其余内容」的方法,需要自行编写自定义转义逻辑来实现需求。
Vue 默认转义/解析逻辑说明
- 使用
{{ text }}插值时,Vue 会调用内部的全量转义函数,将所有HTML特殊字符(包括&、<、>等)转换为对应的实体字符,所以 会被转义成&nbsp;,<strong>会被转义成<strong>。 - 使用
v-html指令时,Vue 会直接将内容作为原始HTML插入DOM,不做任何转义,因此所有HTML标签和实体都会被浏览器解析渲染。
自定义实现方案
1. 通用HTML转义函数
首先实现一个标准的HTML转义函数,用于转义除指定字符外的所有HTML特殊字符:
escapeHtml(str) { const escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return str.replace(/[&<>"']/g, match => escapeMap[match]); }
2. 针对目标文本的格式化处理
针对你提供的文本 <strong>something</strong>,可以通过两种方式处理:
方式一:拆分文本保留开头的
适合仅开头存在 的场景:
<p v-html="formatText(text)"></p> <script> export default { data() { return { text: " <strong>something</strong>" } }, methods: { escapeHtml(str) { const escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return str.replace(/[&<>"']/g, match => escapeMap[match]); }, formatText(rawText) { // 匹配开头连续的 const nbspMatch = rawText.match(/^( )+/); // 提取需要保留的 部分 const preservedNbsp = nbspMatch ? nbspMatch[0] : ''; // 提取剩余需要转义的文本 const restContent = rawText.replace(/^( )+/, ''); // 拼接结果:保留的 + 转义后的内容 return preservedNbsp + this.escapeHtml(restContent); } } } </script>
方式二:全局替换保留任意位置的
适合文本中任意位置存在 的场景:
<p v-html="formatText(text)"></p> <script> export default { data() { return { text: " <strong>something</strong> end" } }, methods: { escapeHtml(str) { const escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return str.replace(/[&<>"']/g, match => escapeMap[match]); }, formatText(rawText) { // 用临时标记替换所有 ,避免转义 const tempMarker = '__TEMP_NBSP__'; const tempText = rawText.replace(/ /g, tempMarker); // 转义整个文本 const escapedText = this.escapeHtml(tempText); // 将临时标记替换回 return escapedText.replace(new RegExp(tempMarker, 'g'), ' '); } } } </script>
以上两种方式最终都会输出: <strong>something</strong>(浏览器渲染后显示为两个空格加纯文本<strong>something</strong>),符合你保留 、转义其余HTML的需求。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

