开发者

Stripping out < and > in javascript doesn't quite work

    function SanitizeInput(input) {



        input = in开发者_高级运维put.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


You're 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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜