For sanitizing against XSS, yes. For sanitizing against SQL injections, no.
Is this a good string sanitizer? [duplicate]
-
06-03-2022 - |
题
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();
}
解决方案
其他提示
It's better (and still easy) to remove the jquery 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.
不隶属于 StackOverflow