javascript - 预输入正则表达式无效 :/(/:

标签 javascript typeahead

我添加了预输入搜索。一切正常,但我发现了一个问题。我的 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/

相关文章:

javascript - 无法使用 Selenium 在文本框中插入文本(使用 firefox)

javascript - 使用 javascript 将参数发送到 java 应用程序

JSON对象列表的Angular 6 ngbTypeahead过滤器

javascript - 在范围内使用 Typeahead 和 AngularJS 加载数据会导致 "TypeError: Cannot call method ' then' of undefined"

javascript - 如何引用 bootstrap-typeahead 的数据?

angular - 使用 Angular 2 使用 ag-grid 提前输入

javascript - Three.js:如何制作对比球体?

javascript - 如何实现动态 react 表

javascript - Knockout textInput 和 maskedinput 插件

wpf - 通过键盘 "Type-Ahead"搜索选择 WPF 列表框中的项目