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 ?
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).