// 字符串反转义
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标签,因此就不能直接当做文本中的符号来使用。为了在HTML文档中使用这些符号,就需要定义它的转义字符串。HTML直接显示转义字符一般是由于标签不完整或字符集错误导致的,删除对多余网页本身影响不大。