【问题标题】:How to fix such RegExp bug in jQuery plugin?如何修复 jQuery 插件中的此类 RegExp 错误?
【发布时间】:2012-03-10 15:58:36
【问题描述】:

我在编程语言列表中使用jQuery Tokeninput 自动完成插件,我发现它不能处理“C++”中的“+”字符:它返回一个 JavaScript 错误,并且自动完成列表上没有任何内容。

当我输入“C”时,ir 返回错误:

未捕获的 SyntaxError:无效的正则表达式: /(?![^&;]+;)(?!])(C++)(?![^]>)(?![^&;] +;)/: 没什么好重复的

问题似乎出在a small method with RegExp statement:

function find_value_and_highlight_term(template, value, term) {
    return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}

变量:

template = "<li>C++</li>";
value = "C++";
term = "C";

我该如何解决?

【问题讨论】:

    标签: javascript jquery-tokeninput


    【解决方案1】:

    + 是正则表达式中的一个特殊修饰符,意思是“匹配一个或多个前面的东西”。要匹配文字 '+' 字符,请使用 \ 对其进行转义

    /(?![^&;]+;)(?!<[^<>])(C\+\+)(?![^<>]>)(?![^&;]+;)/
    

    转义所有特殊字符:

    function escapeRegex(str) {
      return str.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, '\\$&');
    }
    
    var re = new RegExp(escapeRegex('[.*?]'));
    

    【讨论】:

    • 有什么方法可以使任何字符串正则表达式安全吗?例如:(" + regexp_safe(value) + ")
    • 找到它:simonwillison.net/2006/Jan/20/escape/#p-6 - 现在工作正常。谢谢。
    • @Apolo 我添加了一个函数
    【解决方案2】:

    只需将该正则表达式函数替换为该函数的 splice 和 strpos 版本即可。 它工作得更好更快,它不会有任何特殊字符的问题。

    函数如下:

    function find_value_and_highlight_term(template, value, term) {
      var templateLc = template.toLowerCase();
      var strpos = templateLc.indexOf(term);
      if(strpos) {
        var strlen = term.length;
        var templateStart = template.slice(0,strpos);
        var templateEnd = template.slice(strpos+strlen);
        return templateStart+"<b>"+term+"</b>"+templateEnd;
      } else {
        return template;
      }
    }
    

    【讨论】:

    • 这并不是 OP 真正想要的。
    • 我真的不明白为什么我的答案无效...OP想要解决问题...与该特定插件相关...第一个也是投票最多的答案无法正常工作!插件停止以突出显示搜索到的文本...所以我的解决方案更好....我真的不明白为什么这么挑剔没有一个很好的理由....问题是什么??是如何修复这个插件吗?或者它是关于正则表达式的哲学???请回答,如果您仍然认为我的回答无效,我将避免浪费任何其他时间来提供帮助............!
    【解决方案3】:
    Here I have found solution of "c++" string during searching in tokeninput js.
    you just search code in jquery.tokeninput.js and replace with code below.
    
    here are the function:
    
     function regexSanitize( str ) {
       return str.replace(/([.+*?:\[\](){}|\\])/g, "\\$1");
      }
    
      function highlight_term(value, term) {
        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexSanitize(value) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<b>$1</b>");
        }
    
    
    
     function find_value_and_highlight_term(template, value, term) {
           return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexSanitize(value) + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term)
    );
    

    }

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多