1

Possible Duplicate:
HtmlSpecialChars equivalent in Javascript?

I couldn't find a good string sanitization function to be safely used inside HTML. I was wondering if this is a good approach:

String.prototype.sanitize = function() {
  return $('<div></div>').text(this).html();
}
Community
  • 1
  • 1
PH.
  • 536
  • 7
  • 17

2 Answers2

4

For sanitizing against XSS, yes. For sanitizing against SQL injections, no.

Josh Austin
  • 740
  • 3
  • 14
1

It's better (and still easy) to remove the requirement:

String.prototype.htmlspecialchars = function() {
  var span = document.createElement('span'),
  txt = document.createTextNode(this);

  span.appendChild(txt);

  return span.innerHTML;
}

The coupling with document still isn't so bad, because that's where it's going to be used anyway, but I prefer using successive String.replace() like in this answer.

Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309