js实现encodeHTML和decodeHTML

HTML编解码说明/在线HTML编解码

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(`&amp;&lt;p&gt;aaa&lt;/p&gt;`)

HTML编码(encodeHTMl)

对HTML编码就是对HTML文档中的特殊字符进行编码, 使得浏览器不会将这些内容识别为HTML文档内容;

会变编码的字符如

  • &: &amp
  • <: &lt;
  • >: &gt

HTML解码(decodeHTML)

HTML编码的逆过程, 将HTML中进行过编码的字符恢复为原来的字符

  • &amp: &
  • &lt;: <
  • &gt: >
原文地址:https://www.cnblogs.com/Laggage/p/14182354.html