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


当前回答

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

例如:

http://jsfiddle.net/9H6Ch/

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

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

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

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

其他回答

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

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

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

console.log(strippedString);

使用Lodash:

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

源代码

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

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

显示未编码文本的最简洁和有效的方法是使用textContent属性。

比使用innerHTML更快。这还没有考虑到逃逸开销。

document.body.textContent = 'a <b> c </b>';