🌙花开花落花无悔🌙
🌙缘来缘去缘如水🌙
🕳在 Vue 中,转义的 html,v-html
是解析不了🕳
后端(Java)
<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
属性
// 转义
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)) // <p><b>月&月牙坠</b></p>
// 反转义
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) // <p><b>月&月牙坠</b></p>
console.log(HTMLDecode(escapeText)) // <p><b>月&月牙坠</b></p>