Javascript - 正则表达式/替换优化

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, '&#8217;' ).replace( /&#039;/g, '&#8217;' ).replace( /[\u2019]/g, '&#8217;' );
    text = text.replace( /"/g, '&#8221;' ).replace( /&#034;/g, '&#8221;' ).replace( /&quot;/g, '&#8221;' ).replace( /[\u201D]/g, '&#8221;' );
    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( /'|&#039;|[\u2019]/g, '&#8217;');
    text = text.replace( /"|&#034;|&quot;|[\u201D]/g, '&#8221;' )
    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(/'|&#039;|[\u2019]/g.test(text))
        text = text.replace( /'|&#039;|[\u2019]/g, '&#8217;');
    while(/"|&#034;|&quot;|[\u201D]/g.test(text))
        text = text.replace( /"|&#034;|&quot;|[\u201D]/g, '&#8221;' )
    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的注释范围内,可能会慢一些。查看性能演示