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

html-css05

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);

输出:

转义字符有很多,在实际编程过程中常常会用到,那么下面介绍一下常用的转义字符。

1、首先打开pycharm,新建一个工程和python文件,如图。

2、打印一段话,输入print添加内容,如下图所示。

3、接着转义字符"\n"换行,如图所示,转义字符"\t"制表符。

4、然后转义字符"\""双引号和"\'"单引号,如下图所示。

5、最后转义字符"\r"回车,如下图所示就完成了。