Pregunta

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();
}
¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top