我添加了预输入搜索。一切正常,但我发现了一个问题。我的 json 中有文本,例如“嗨,我的名字是 Jason (Mckay) 和 ...”
当我尝试从此字符串中键入一些单词时,一切都可以,但是当我键入“(”或“)”时,我会遇到异常:
Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group
我正在查看预先输入的“基础知识”并遇到相同的错误:
https://twitter.github.io/typeahead.js/examples/#prefetch
当我尝试先输入任何数字 "1"、"2" 等时也是如此...
这是我的默认 substringMatcher 问题出在哪里:
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring 'q', add it to the 'matches' array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
最佳答案
使用正则表达式会很痛苦,因为所有“特殊”字符如 ( [ 等
你的代码似乎足够简单,无论如何都不使用 RegExp - indexOf 应该可以解决问题
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
q = q.toLowerCase();
var matches = strs.filter(function(str) {
return str.toLowerCase().indexOf(q) >= 0;
});
cb(matches);
};
};
是的,ES2015+ 有 String#includes 方法,使用起来更有意义 - 但为什么不使用 ES2015+ 的所有好处
const substringMatcher = strs => (q, cb) => {
q = q.toLowerCase();
cb(strs.filter(str => str.toLowerCase().includes(q)));
};
或者效率较低(toLowerCase 调用的次数超出了需要,但代码更性感
const substringMatcher = strs => (q, cb) => cb(strs.filter(str => str.toLowerCase().includes(q.toLowerCase())));
关于javascript - 预输入正则表达式无效 :/(/:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41142614/