To avoid many attacks, you should pay attention to what type of content you're manipulating. What looks like text is not necessarily text. This applies both for SQL (SQL Injection) and HTML (XSS).
abc is written
abc as text. It is also written
abc as HTML. So you may think that if you have text to display, you can just concatenate it with the rest of your HTML. But no, you can't.
The issue is that some characters have a special meaning in HTML. The biggest issue is
& is also a problem, and you want to avoid a few others for various reasons, including
> and quotes, if what you are writing is an HTML attribute.
So, what you need to do is convert your text to HTML before you insert it into HTML: text is not HTML, and HTML is not text.
In some languages you have standard functions to do this, such as PHP's
htmlspecialchars which you should use on every single piece of text you insert into HTML.
You don't write HTML. You shouldn't anyway. You should create DOM elements, then set attributes on them, or set the text contents of them. If you use jQuery, that means you shouldn't write:
// XXX DON'T DO THIS! EVER!
You should instead write:
You shouldn't use
Likewise, don't do this:
// XXX DON'T DO THIS
Do this instead:
Or, if you really want to write HTML, then you need to convert all your text to HTML to do that. This means at the very least replacing:
&, but you also want to replace
' if that will end up in an attribute (easier to always do it). A regex replacement will do.
JSON.stringify will not help you here.