Can I escape html special chars in javascript?

后端 未结 15 1424
隐瞒了意图╮
隐瞒了意图╮ 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:00
    function escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
     }
    
    0 讨论(0)
  • 2020-11-22 03:01

    If you already use modules in your app, you can use escape-html module.

    import escapeHtml from 'escape-html';
    const unsafeString = '<script>alert("XSS");</script>';
    const safeString = escapeHtml(unsafeString);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 03:02

    Try this, using the prototype.js library:

    string.escapeHTML();
    

    Try a demo

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

    DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.

    document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';
    
    0 讨论(0)
  • 2020-11-22 03:05

    You can use jQuery's .text() function.

    For example:

    http://jsfiddle.net/9H6Ch/

    From the jQuery documentation regarding the .text() function:

    We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.

    Previous Versions of the jQuery Documentation worded it this way (emphasis added):

    We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <).

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