html转义反转义

html-css07

html转义反转义,第1张

// 字符串反转义

function enXssHtml(text) {

const matchList = {

"<": "<",

">": ">",

"&": "&",

"": '""',

""": '"',

"'": "'",

}

let regStr = "(" + Object.keys(matchList).toString() + ")"

// ↑ ------------【 提取匹配列表key值 】.【组数转字符串】

regStr = regStr.replace(/,/g, ")|(")

// ↑ 通过匹配将其更新为正则的字符串类型

const regExp = new RegExp(regStr, "g")

// ↑ ------- 字符串 转 正则 方法

return text.replace(regExp, (match) =>matchList[match])

// ↑ ------ 替换方法 (正则, 当前key =>返回当前被匹配的key值)

}

// 字符串反转义

function deXssHtml(text) {

const matchList = {

"<": "<",

">": ">",

"&": "&",

'"': '"',

'"': '"',

"'": "'",

}

let regStr = "(" + Object.keys(matchList).toString() + ")"

// ↑ ------------【 提取匹配列表key值 】.【组数转字符串】

regStr = regStr.replace(/,/g, ")|(")

// ↑ 通过匹配将其更新为正则的字符串类型

const regExp = new RegExp(regStr, "g")

// ↑ ------- 字符串 转 正则 方法

return text.replace(regExp, (match) =>matchList[match])

// ↑ ------ 替换方法 (正则, 当前key =>返回当前被匹配的key值)

}

HTML的常用的如:<>&"©分别是<,>,&,",©的转义字符

当然还有很多其他的,可以查看对照表解决。

转义的目的就是为了防止冲突或者代码被浏览器执行了。

Html中特殊字符不被转义,可以使用预格式化标签。pre 是 Preformatted text(预格式化文本) 的缩写。使用此标签可以把代码中的空格和换行直接显示到页面上。例如HTML代码: 

<pre> if (xx >5) { print "比5大!\n" } </pre>

浏览器显示效果:if (xx >5) {print "比5大!\n"}<textarea></textarea>之间包含有类似的这种转义字符的时候总会被解析,倒是可以把所有的"&"通过程序替换成"&",但是有些本来就是"&"的也会被转换,这就错了。如何让<textarea></textarea>之间包含的文本原封不动的显示出来呢?总结如下:解决方法有两种:第1种:

<body><textarea id='t' rows=20 cols=20></textarea><script>document.getElementById('t').innerText='a<&>'</script></body>

第2种:/*将字串转为html格式*/ 

public String strToHtml(String s) { if (s==null||s.equals("")) return "" s = s.replaceAll("&", "&") s = s.replaceAll("<", "<") s = s.replaceAll(">", ">") s = s.replaceAll(" ", " ") // s = s.replaceAll("/n", "") // s = s.replaceAll("'", "'") return s } /*将html格式转为字串*/ public String strToHtml(String s) { if (s==null||s.equals("")) return "" s = s.replaceAll("&","&") s = s.replaceAll("<","<") s = s.replaceAll(">",">") s = s.replaceAll(" "," ") //s = s.replaceAll("","/n") //s = s.replaceAll("'","'") return s }

最后一点:jQuery的.html()方法默认会转义的,这种情况使用.text()就不会转义了。