代码
// 使用js实现 转义&还原HTML
const htmlStr = '<h1 title="123">这是一个h1标题<span>abc </span></h1>';
// 定义转义html的方法
function htmlEscape(htmlStr) {
return htmlStr.replace(/<|>|"|&/g, match =>{
switch(match) {
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '&':
return '&';
}
})
}
// 定义还原html的方法
function htmlUnescape(html) {
return html.replace(/<|>|"|&/g, match => {
switch(match) {
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '&':
return '&';
}
})
}
// 验证方法的正确性
let html = htmlEscape(htmlStr);
console.log(html);
let str = htmlUnescape(html);
console.log(str);
结果