// 字符串反转义
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 标签的文字,直接发出去是对应的显示,例如我发 <button></button >在气泡聊天框中出来的是按钮,我想了很多方法,感觉都不合适,请问如何有效的过滤并且还能正常显示所发出的文案