CFXIXI工作室首页
CF西西的博客 | JS防止脚本注入(替换特殊字符)

JS防止脚本注入(替换特殊字符)

10. 四月 2013
htmlEncode: (function() {
        var entities = {
            '&': '&',
'>': '>',
'<': '&lt;',
'"': '&quot;'
}, keys = [], p, regex; for (p in entities) { keys.push(p); } regex = new RegExp('(' + keys.join('|') + ')', 'g'); return function(value) { return (!value) ? value : String(value).replace(regex, function(match, capture) { return entities[capture]; }); }; })()

使用时再将html字符转回

 htmlDecode: (function() {
            var entities = {
                '&amp;': '&',
                '&gt;': '>',
                '&lt;': '<',
                '&quot;': '"'
            }, keys = [], p, regex;

            for (p in entities) {
                keys.push(p);
            }

            regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');

            return function(value) {
                return (!value) ? value : String(value).replace(regex, function(match, capture) {
                    if (capture in entities) {
                        return entities[capture];
                    } else {
                        return String.fromCharCode(parseInt(capture.substr(2), 10));
                    }
                });
            };
        })(),

javascript