Can I escape html special chars in javascript?

后端 未结 15 1415
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 02:26

I want to display a text to HTML by a javascript function. How can I escape html special chars in JS? Is there an API ?

相关标签:
15条回答
  • 2020-11-22 03:05

    This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.

    function escapeHTML(unsafeText) {
        let div = document.createElement('div');
        div.innerText = unsafeText;
        return div.innerHTML;
    }
    
    0 讨论(0)
  • 2020-11-22 03:06

    The most concise and performant way to display unencoded text is to use textContent property.

    Faster than using innerHTML. And that's without taking into account escaping overhead.

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

    0 讨论(0)
  • 2020-11-22 03:07

    It was interesting to find a better solution:

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

    I do not parse > because it does not break XML/HTML code in the result.

    Here are the benchmarks: http://jsperf.com/regexpairs Also, I created a universal escape function: http://jsperf.com/regexpairs2

    0 讨论(0)
  • 2020-11-22 03:07

    Came across this issue when building a DOM structure. This question helped me solve it. I wanted to use a double chevron as a path separator, but appending a new text node directly resulted in the escaped character code showing, rather than the character itself:

    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 */
    
    0 讨论(0)
  • 2020-11-22 03:10

    function escapeHtml(html){
      var text = document.createTextNode(html);
      var p = document.createElement('p');
      p.appendChild(text);
      return p.innerHTML;
    }
    
    // Escape while typing & print result
    document.querySelector('input').addEventListener('input', e => {
      console.clear();
      console.log( escapeHtml(e.target.value) );
    });
    <input style='width:90%; padding:6px;' placeholder='&lt;b&gt;cool&lt;/b&gt;'>

    0 讨论(0)
  • 2020-11-22 03:15

    Using lodash

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

    source code

    0 讨论(0)
提交回复
热议问题