html转义反转义

html-css025

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

}

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>

asp用Server.HTMLEncode

<%response.write(Server.HTMLEncode("The image tag: <img>"))%>

javascript 用正则表达式进行转换处理

var HtmlUtil = {

/*1.用正则表达式实现html转码*/

htmlEncodeByRegExp:function (str){

var s = ""

if(str.length == 0) return ""

s = str.replace(/&/g,"&")

s = s.replace(/</g,"<")

s = s.replace(/>/g,">")

s = s.replace(/ /g," ")

s = s.replace(/\'/g,"'")

s = s.replace(/\"/g,""")

return s

},

/*2.用正则表达式实现html解码*/

htmlDecodeByRegExp:function (str){

var s = ""

if(str.length == 0) return ""

s = str.replace(/&/g,"&")

s = s.replace(/</g,"<")

s = s.replace(/>/g,">")

s = s.replace(/ /g," ")

s = s.replace(/'/g,"\'")

s = s.replace(/"/g,"\"")

return s

}

}