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


当前回答

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

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

其他回答

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

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

我想出了这个解决方案。

假设我们想向元素添加一些HTML,其中包含来自用户或数据库的不安全数据。

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + unsafe + '</p>';
html += '</div>';

element.html(html);

它对于XSS攻击是不安全的。现在加上这个: $ (document.createElement (div)) . html(不安全)。text ();

就是这样

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>';
html += '</div>';

element.html(html);

对我来说,这比使用.replace()容易得多,它会删除!!所有可能的HTML标签(我希望)。

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

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

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

使用Lodash:

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

源代码