tags:

views:

82

answers:

4
    function SanitizeInput(input) {



        input = input.replace(/</g, "&lt;");
        input = input.replace(/>/g, "&gt;");


        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

+3  A: 

There has to be something else in your layout/document affecting this, your code itself works fine, you can test it here.

Nick Craver
Doesn’t work from `onload`.
jleedev
@jleedev - `document.write` doesn't work reliably outside inline script at all...it's just an example I believe.
Nick Craver
@Nick Here we go: http://jsfiddle.net/gsj6L/
jleedev
@jleedev - Yeah...you can't use `document.write` like that...*where* would you be writing it? The function itself works, here's your version with an alert instead: http://jsfiddle.net/nick_craver/gsj6L/1/
Nick Craver
@Nick Yes, I was mainly trying to read the OP’s mind. Using `document.write` in that way *is* well-defined in HTML5, though. http://www.w3.org/TR/html5/apis-in-html-documents.html#document.write
jleedev
@jleedev - This well-defined way will write the content after `</html>`, that wasn't the W3C's intent on *how it should be used*, they're just keeping the behavior consistent when it *is* used that way by specifying it.
Nick Craver
+1  A: 

if you are trying to sanitize input, try something like this - http://xkr.us/articles/javascript/encode-compare/

brian brinley
+2  A: 

Hello!

Your not doing anything wrong. The function you use does replace all your < with &lt; and > with &gt;. 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 &lt; visible in your page you should "double-sanitize" the text. input = input.replace(/</g, "&amp;lt;");

On a side note you could chain replace calls, like this: input = input.replace(/</g, "&lt;").replace(/>/g, "&gt;");

Hope you find this useful, Alin

Alin Purcaru
A: 

Try to escape < and >, since they aren't supposed to be inside a < script >-tag (however browsers usually compensate for this common error).

input = input.replace(/\x3c/g, "&lt;").replace(/\x3e/g,"&gt;");
some
By the way, you should also translate codes...
some