Can I escape html special chars in javascript?

后端 未结 15 1699
隐瞒了意图╮
隐瞒了意图╮ 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: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('»');
    //_div.appendChild(_separator); /* this resulted in '»' being displayed */
    _div.innerHTML = _separator.textContent; /* this was key */
    

提交回复
热议问题