Can I escape html special chars in javascript?

后端 未结 15 1608
隐瞒了意图╮
隐瞒了意图╮ 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: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  here';
    
    var html = '';
    html += '
    '; html += '

    ' + unsafe + '

    '; html += '
    '; 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  here';
    
    var html = '';
    html += '
    '; html += '

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

    '; html += '
    '; element.html(html);

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

提交回复
热议问题