node07_自定义一个html转义模块
在日常开发的过程中除了转换时间之外,我们可能还会遇到需要将html代码转义成文本,以及将文本转义成html的需求,下面我们来自定义一个转义的模块。
具体的思路就是使用正则表达式,找到对应的要转义的字符进行转义即可。
function htmlEsplace(htmlstr) {
//定义转义html方法
return htmlstr.replace(/<|>|"|&/g, (match) => {
switch (match) {
case '<':
return '<'
case '>':
return '>'
case '"':
return '"'
case '&':
return '&'
}
})
}
function reductionHtml(str){
//还原HTML的方法
return str.replace(/<|>|"|&/g,(match)=>{
switch (match){
case '<':
return '<'
case '>':
return '>'
case '"':
return '"'
case '&':
return '&'
}
})
}
module.exports={
reductionHtml,
htmlEsplace
}
引入并使用