我正在为编程语言列表使用jQuery托肯输入自动完成插件,我发现它不处理“C++”中的"+“字符:它返回一个JavaScript错误,自动完成列表中没有显示任何内容。
当我输入"C“ir时,返回错误:
未知SyntaxError:无效正则表达式: /(?+;)(?!<^<>)(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";
我该怎么解决呢?
发布于 2012-03-10 08:00:39
+
是正则表达式中的一个特殊修饰符,意思是“匹配一个或多个先前的事物”。若要与文字'+'
字符匹配,请使用\
转义它。
/(?![^&;]+;)(?!<[^<>])(C\+\+)(?![^<>]>)(?![^&;]+;)/
要转义所有特殊字符:
function escapeRegex(str) {
return str.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, '\\$&');
}
var re = new RegExp(escapeRegex('[.*?]'));
发布于 2016-03-04 02:15:35
只需将regexp函数替换为该函数的拼接和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;
}
}
发布于 2016-07-06 05:00:11
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)
);
}
https://stackoverflow.com/questions/9647830
复制相似问题