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 ?
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 &ersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55">www.WHAK.com</textarea>
Use this to remove HTML tags from string in JavaScript:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
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).