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


当前回答

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

其他回答

找到一个更好的解决方案是很有趣的:

var escapeHTML = function(unsafe) {
  return unsafe.replace(/[&<"']/g, function(m) {
    switch (m) {
      case '&':
        return '&amp;';
      case '<':
        return '&lt;';
      case '"':
        return '&quot;';
      default:
        return '&#039;';
    }
  });
};

我没有解析>,因为它没有破坏结果中的XML/HTML代码。

以下是基准测试:http://jsperf.com/regexpairs 此外,我还创建了一个通用转义函数:http://jsperf.com/regexpairs2

我在构建DOM结构时遇到了这个问题。这个问题帮助我解决了这个问题。我想使用双雪佛龙作为路径分隔符,但追加一个新的文本节点直接导致转义字符代码显示,而不是字符本身:

var _div = document.createElement('div');
var _separator = document.createTextNode('&raquo;');
//_div.appendChild(_separator); /* This resulted in '&raquo;' being displayed */
_div.innerHTML = _separator.textContent; /* This was key */

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

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

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

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

使用Lodash:

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

源代码