简体   繁体   English

如何在键入列表时按过滤器中的空间过滤?

[英]How to filter by space in filter as you type list?

I want to filter a list by typing a space (just like any other character). 我想通过输入空格来过滤列表(就像其他任何字符一样)。

The current code is: 当前代码是:

var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));

If I have vege tables in my list and I type a space, or letter e and space, or space and letter t , the list should filter to show vege tables . 如果我的列表中有vege tables ,并且输入空格,字母e和空格,空间和字母t ,则列表应进行过滤以显示vege tables

I have tried to add \\s to the code but it is not working as I had hoped: 我试图将\\ s添加到代码中,但是它没有按我希望的那样工作:

var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\s]/g, "\\$&"));

Am I missing something? 我想念什么吗?

Here's an example of how to filter a list of stings based on a pattern. 这是一个如何根据模式过滤filter列表的示例。

function filter(list, pattern) {
  return list.filter(function(item) {
    return pattern.test(item);
  });
}
const list = ['vege tables', 'man eater', 'word'];
console.log('Current list: ', list);

var pattern = ' e';
console.log('Filter by: "' + pattern + '"');

pattern = new RegExp(pattern, 'gi'); // convert the pattern to regex
console.log(filter(list, pattern)); // get filtered list, ['man eater']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM