Can I escape html special chars in javascript?

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

    You can encode every character in your string:

    function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
    

    Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

    function encode(r){
    return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
    }
    
    test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');
    
    /*************
    * \x26 is &ampersand (it has to be first),
    * \x0A is newline,
    *************/
    <textarea id=test rows="9" cols="55">&#119;&#119;&#119;&#46;&#87;&#72;&#65;&#75;&#46;&#99;&#111;&#109;</textarea>

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

    Use this to remove HTML tags from string in JavaScript:

    const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
    
    console.log(strippedString);
    
    0 讨论(0)
  • 2020-11-22 03:25

    I came up with this solution.

    Let's assume that we want to add some html to the element with unsafe data from the user or database.

    var unsafe = 'some unsafe data like <script>alert("oops");</script> here';
    
    var html = '';
    html += '<div>';
    html += '<p>' + unsafe + '</p>';
    html += '</div>';
    
    element.html(html);
    

    It's unsafe against XSS attacks. Now add this.

    $(document.createElement('div')).html(unsafe).text();
    

    So it is

    var unsafe = 'some unsafe data like <script>alert("oops");</script> here';
    
    var html = '';
    html += '<div>';
    html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>';
    html += '</div>';
    
    element.html(html);
    

    To me this is much easier than using .replace() and it'll remove!!! all possible html tags (I hope).

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