0

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

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

未捕获的语法错误:无效的正则表达式:/(?![^&;]+;)(?!<[^<>] )(C++)(?![^<>] >)(?![^&;] +;)/: 没什么可重复的

问题似乎在于RegExp 语句的一个小方法

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";

我如何解决它?

4

3 回答 3

3

+是正则表达式中的一个特殊修饰符,意思是“匹配一个或多个先前的事物”。要匹配文字'+'字符,请使用\

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

转义所有特殊字符:

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

var re = new RegExp(escapeRegex('[.*?]'));
于 2012-03-10T16:00:39.623 回答
0

只需用该函数的 splice 和 strpos 版本替换该 regexp 函数。它工作得更好更快,它不会有任何特殊字符的问题。

这是功能:

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;
  }
}
于 2016-03-04T10:15:35.787 回答
0
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)
);

}

于 2016-07-06T13:00:11.540 回答