Javascript - Regex/replace 优化

Javascript - Regex/replace optimization

我有一个脚本允许替换不需要的 HTML 标签和转义引号以 "improve" 安全并主要防止脚本标签和加载注入等....该脚本用于 "texturize" 从 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, '=""' );
    return text.trim();

};

编辑: 这里是 fiddle:https://fiddle.jshell.net/srnoe3s4/1/。 Fiddle 显然不喜欢 javascript 字符串中的 script 标签,所以我没有添加它。

我将只处理性能和简单的安全检查,因为编写消毒程序不是您可以在 table 的角落做的事情。如果你想节省时间,避免多次调用 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, '=""' );
    return text.trim();
};

如果你考虑到 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, '=""' );
    return text.trim();
};

在标准测试用例中,这不会比之前的代码慢很多。但是如果输入在dan1111的注释范围内,可能会比较慢。参见 perf demo