JS实现HTML标签转义及反转义

html-css010

JS实现HTML标签转义及反转义,第1张

function HTMLEncode(html) {

    var temp = document.createElement("div")

    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html)

    var output = temp.innerHTML

    temp = null

    return output

}

var tagText = "<p><b>123&456</b></p>"

console.log(HTMLEncode(tagText))//<p><b>123&456</b></p>

function HTMLDecode(text) { 

       var temp = document.createElement("div")

        temp.innerHTML = text 

        var output = temp.innerText || temp.textContent

        temp = null 

        return output

var  tagText = "<p><b>123&456</b></p>"

var  encodeText=HTMLEncode(tagText)

console.log(encodeText)      //<p><b>123&456</b></p>

console.log(HTMLDecode(encodeText))    //<p><b>123&456</b></p>

json的Marshal 用来对slice,map,struct等结构化类型数据转义成[]byte/string,UnMarshal方法是用来对[]byte/string转义成指定结构的interface。但在处理html标签字符中,会存在转义问题。Marshal方法默认把html标签中的'<', '>' , '&'字符转义成unicode,为强制为有效UTF-8的JSON字符串,用Unicode替换符号替换无效字节。

go doc原文

Marshal的源码

这一行encOpts{escapeHTML: true}),这里的true导致标签被转义。

针对上述问题,有两种解决办法,第一种是替换上述三个tag,第二种是SetEscapeHtml(false);

输出: