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


当前回答

函数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; " >

其他回答

只写代码之间<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>

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

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;');
}

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

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

console.log(strippedString);

你可以使用jQuery的.text()函数。

例如:

http://jsfiddle.net/9H6Ch/

来自jQuery文档关于.text()函数:

我们需要意识到这种方法 转义提供的字符串 必须这样才能渲染 正确的HTML格式。为了做到这一点,它调用 DOM方法。createtextnode () 不会将字符串解释为HTML。

以前版本的jQuery文档是这样写的(强调添加):

我们需要知道这个方法在必要时转义提供的字符串,以便在HTML中正确呈现。为此,它调用DOM方法. createtextnode(),该方法将特殊字符替换为对应的HTML实体(例如&amplt表示<)。

DOM元素支持通过赋值innerText将文本转换为HTML。innerText不是一个函数,但是给它赋值就好像文本被转义了一样。

document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';