我想通过JavaScript函数将文本显示为HTML。如何在JavaScript中转义HTML特殊字符?有API吗?


当前回答

这是目前为止我见过的最快的方法。另外,它不需要在页面上添加、删除或更改元素。

function escapeHTML(unsafeText) {
    let div = document.createElement('div');
    div.innerText = unsafeText;
    return div.innerHTML;
}

其他回答

函数escapeHtml (html) { var text = document.createTextNode(html); var p = document.createElement('p'); p.appendChild(文本); 返回p.innerHTML; } //在输入时转义并打印结果 document.querySelector(“输入”)。addEventListener('input', e => { console.clear (); console.log(escapeHtml(e.t target.value)); }); <输入风格= '宽度:90%;填充:6 px;占位符= ' & lt; b&gt; cool&lt; / b&gt; " >

这里有一个几乎适用于所有浏览器的解决方案:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

如果你只支持现代浏览器(2020+),那么你可以使用新的replaceAll函数:

const escapeHtml = (unsafe) => {
    return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');
}

如果你已经在你的应用程序中使用模块,你可以使用escape-html模块。

import escapeHtml from 'escape-html';
const unsafeString = '<script>alert("XSS");</script>';
const safeString = escapeHtml(unsafeString);

在JavaScript中删除字符串中的HTML标签:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");

console.log(strippedString);

只写代码之间<pre><code class="html-escape">....</code></pre>。确保在代码标记中添加了类名。它将转义所有编写的HTML代码片段 < pre > <代码类= " html-escape " >…< /代码> < / >。

const escape = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;', } const codeWrappers = document.querySelectorAll('.html-escape') if (codeWrappers.length > 0) { codeWrappers.forEach(code => { const htmlCode = code.innerHTML const escapeString = htmlCode.replace(/"|&|<|>/g, function (matched) { return escape[matched]; }); code.innerHTML = escapeString }) } <pre> <code class="language-html html-escape"> <div class="card"> <div class="card-header-img" style="background-image: url('/assets/card-sample.png');"></div> <div class="card-body"> <p class="card-title">Card Title</p> <p class="card-subtitle">Srcondary text</p> <p class="card-text">Greyhound divisively hello coldly wonderfully marginally far upon excluding.</p> <button class="btn">Go to </button> <button class="btn btn-outline">Go to </button> </div> </div> </code> </pre>