encodeHTMl
const encodeHTML = (html: string): string => {
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
const decodeHTML = (html: string): string => {
const div = document.createElement('div');
div.innerHTML = html;
return div.innerText || div.innerHTML;
}
const html = '<p>html decode/encode test &</p>';
let encodedHTML = encodeHTML(html);
let decodedHTML = decodeHTML(encodedHTML);
console.log(`raw html: ${html}`);
console.log(`encoded html: ${encodedHTML}`);
console.log(`decoded html: ${decodedHTML}`);
console.log(`&<p>aaa</p>`)
HTML编码(encodeHTMl)
对HTML编码就是对HTML文档中的特殊字符进行编码, 使得浏览器不会将这些内容识别为HTML文档内容;
会变编码的字符如
- &:
&
- <:
<
- >:
>
HTML解码(decodeHTML)
HTML编码的逆过程, 将HTML中进行过编码的字符恢复为原来的字符
&
: &<
: <>
: >