Can I escape html special chars in javascript?

后端 未结 15 1428
隐瞒了意图╮
隐瞒了意图╮ 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:02

    I think I found the proper way to do it...

    // Create a DOM Text node:
    var text_node = document.createTextNode(unescaped_text);
    
    // Get the HTML element where you want to insert the text into:
    var elem = document.getElementById('msg_span');
    
    // Optional: clear its old contents
    //elem.innerHTML = '';
    
    // Append the text node into it:
    elem.appendChild(text_node);
    

提交回复
热议问题