Stripping out < and > in javascript doesn't quite work
function SanitizeInput(input) {
input = in开发者_高级运维put.replace(/</g, "<");
input = input.replace(/>/g, ">");
return input;
}
document.write(SanitizeInput("Test!<marquee>bibble</marquee>"));
If you pop this into jsfiddle.net the result is Test!<marquee>bibble</marquee
without the trailing >
Can anyone explain what I'm doing wrong?
Edit: Replacing it with ( and ) seems to work perfectly
You're not doing anything wrong. The function you use does replace all your <
with <
and >
with >
. Just that document.write adds the sanitized text to the HTML document and the entities get converted back to <
and >
.
Just try alert
instead of document.write
.
If you really want to have <
visible in your page you should "double-sanitize" the text.
input = input.replace(/</g, "&lt;");
On a side note you could chain replace calls, like this:
input = input.replace(/</g, "<").replace(/>/g, ">");
Hope you find this useful,
Alin
There has to be something else in your layout/document affecting this, your code itself works fine, you can test it here.
if you are trying to sanitize input, try something like this - http://xkr.us/articles/javascript/encode-compare/
精彩评论