1

I am creating a website, and I have a section where the user can provide input via a form. The input is sanitized using this:

str.replace(/[\x26\x0A<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})

After that, the data is placed between <p> tags. So something like this:

<p id="foo">Random message</p>

Is my replacement function good enough to prevent an XSS attack?

JJ Binks
  • 21
  • 2
  • 2
    Don't sanitize yourself. Use JavaScript's `innerText` and you are safe. – m1k1o Mar 22 '20 at 20:02
  • @M1K1O I will look into that. Is my current function safe though? – JJ Binks Mar 22 '20 at 20:22
  • Rather, use `textContent` if you're setting content. – Mike 'Pomax' Kamermans Mar 22 '20 at 20:39
  • @Mike'Pomax'Kamermans They behave differently and both can be appropriate for different uses. E.g. when setting `innerText` to a string containing a newline, the newline is visible (as a `
    `), but if you used `textContent` the newline is ignored.
    – GKFX Mar 22 '20 at 20:44
  • 1
    That's not the true difference: `innerText` is only the node's text, and only _visible_ text, whereas `textContent` is the full tree text content. For getting, you need to make a judgement call on which of the two to use (and even then, usually it's `textContent`). When setting, just use `textContent`, because HTML doesn't care about newlines until you force it to care by giving it CSS that does that (e.g. set `white-space: pre" and you get to see all whitespace including newlines. Which you should almost never need, write proper elements and CSS instead) – Mike 'Pomax' Kamermans Mar 22 '20 at 20:50

1 Answers1

1

This is basically a duplicate of Can I escape html special chars in javascript?. Yes your code is probably safe, it does the same as what the accepted answer there does.

GKFX
  • 1,386
  • 1
  • 11
  • 30