文章

HTML转义与反转义(前后端解决方案)

🕳在 Vue 中,转义的 html,v-html 是解析不了🕳

后端(Java)

1
2
3
4
5
6
7
8
9
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>
// 转义
StringEscapeUtils.escapeHtml4(htmlText);
// 反转义
StringEscapeUtils.unescapeHtml4(escapeText);

前端

👀 注:火狐与IE低版本不支持innerText,需要使用textContent属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 转义
function HTMLEncode(htmlText) {
    var temp = document.createElement("div")
    (temp.textContent != null) ? (temp.textContent = htmlText) : (temp.innerText = htmlText)
    var escapeText = temp.innerHTML
    temp = null
    return escapeText
}

var htmlText = "<p><b>月&月牙坠</b></p>";
console.log(HTMLEncode(htmlText)) // &lt;p&gt;&lt;b&gt;月&amp;月牙坠&lt;/b&gt;&lt;/p&gt

// 反转义
function HTMLDecode(escapeText) {
    let temp = document.createElement("div")
    temp.innerHTML = escapeText
    let htmlText = temp.innerText || temp.textContent
    temp = null
    return htmlText
}

var htmlText = "<p><b>月&月牙坠</b></p>"
var escapeText = HTMLEncode(htmlText)
console.log(escapeText) // &lt;p&gt;&lt;b&gt;月&amp;月牙坠&lt;/b&gt;&lt;/p&gt
console.log(HTMLDecode(escapeText)) // <p><b>月&月牙坠</b></p>
本文由作者按照 CC BY 4.0 进行授权