fre*_*aky 5 javascript regex replace sanitization
我有一个脚本,允许替换不需要的HTML标签和转义引号来"提高"安全性,并主要防止脚本标记和onload注入等....这个脚本用于"纹理化"从中检索的内容innerHTML.
但是,它在我的执行时间附近乘以3(在循环中).我想知道是否有更好的方法或更好的正则表达式:
function safe_content( text ) {
text = text.replace( /<script[^>]*>.*?<\/script>/gi, '' );
text = text.replace( /(<p[^>]*>|<\/p>)/g, '' );
text = text.replace( /'/g, '’' ).replace( /'/g, '’' ).replace( /[\u2019]/g, '’' );
text = text.replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /[\u201D]/g, '”' );
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
Run Code Online (Sandbox Code Playgroud)
编辑:这里有一个小提琴:https://fiddle.jshell.net/srnoe3s4/1/.小提琴script显然不喜欢javascript字符串中的标签所以我没有添加它.
Tho*_*oub -1
我将只处理性能和简单的安全检查,因为编写消毒剂不是你可以在桌子一角做的事情。replace()如果您想节省时间,请避免在替换为相同值时多次调用,这会导致您出现以下情况:
function safe_content( text ) {
text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
text = text.replace( /'|'|[\u2019]/g, '’');
text = text.replace( /"|"|"|[\u201D]/g, '”' )
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
Run Code Online (Sandbox Code Playgroud)
如果您考虑到 dan1111 关于奇怪的字符串输入的评论会破坏此实现,您可以添加while(/foo/.test(input))以避免该问题:
function safe_content( text ) {
while(/<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi.test(text))
text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
while(/'|'|[\u2019]/g.test(text))
text = text.replace( /'|'|[\u2019]/g, '’');
while(/"|"|"|[\u201D]/g.test(text))
text = text.replace( /"|"|"|[\u201D]/g, '”' )
while(/([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g.test(text))
text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
return text.trim();
};
Run Code Online (Sandbox Code Playgroud)
在标准测试用例中,这不会比以前的代码慢很多。但如果输入进入dan1111的注释范围内,可能会慢一些。查看性能演示
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |