简体   繁体   中英

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

    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

您的布局/文档中还必须有其他内容来影响这一点,您的代码本身可以正常工作, 您可以在此处进行测试

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

如果您要清理输入内容,请尝试类似以下操作-http://xkr.us/articles/javascript/encode-compare/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM