function htmlEntities(n) {
            return String(n).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
  • Replaces & with &amp;;
  • Replaces < with &lt;
  • Replaces > with &gt;
  • Replaces " with &quot;

If this needs to be more secure, please explain how to break it so I can learn how it can be broken and how to avoid that.

  • 4
    depending on where the string is being printed, the ' should be also replaced, otherwise, the user could escape from attribute (eg : <img src='user input'>) – Xavier59 Sep 3 '16 at 21:46
  • 3
    Are you aware of the standard libraries and approaches to do this? OWASP, for example? – schroeder Sep 3 '16 at 21:51
  • 4
    Have you run this code through XSS cheat sheets? owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet – schroeder Sep 3 '16 at 21:51
  • 2
    Is this for a browser? If so, just use textContent to treat it like text and avoid having to escape. – Alexander O'Mara Sep 3 '16 at 22:38
  • 2
    Why did you write a slightly worse htmlspecialchars()? – rook Sep 4 '16 at 15:27

XSS prevention is all about context. You need different strategies depending on what context the untrusted data you are escaping will be inserted into.

While I think your method would be fine inside HTML elements and in HTML attributes in double quotes, you would have problems in the following contexts:

  • In HTML attributes with single quotes or without quotes at all, you will be pwned.
  • In e.g. a href attribute, you would be pwned with e.g. a javascript: or vbscript: URL.
  • In JavaScript string literals using single quotes, you will be pwned.
  • In JavaScript string literals using double quotes, an attacker could stop the script from being executed by inserting a newline and thereby cause a syntax error. This could have unexpected and adverse consequences in some circumstances.
  • And then there's CSS, which has it's own set of different rules...

For a detailed guide on how to do this right, I strongly recommend the OWASP XSS prevention cheat sheet. I think the main take home lessons of all this is: XSS is complicated. Don't rely on your own home brewed solution to stop it. Use a well tested library instead.

(And Alexander O'Mara is absolutely right in his comment. If this is in the browser, just go with textContent.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.