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

JavaScript011

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>

js中的特殊字符,加上转义符\ 。

例如:

var txt="We are the so-called "Vikings" from the north." document.write(txt) 【错误】

var txt="We are the so-called \"Vikings\" from the north." document.write(txt) 【正确】