Can I escape html special chars in javascript?

后端 未结 15 1673
隐瞒了意图╮
隐瞒了意图╮ 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: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) );
    });

提交回复
热议问题