ES6: Filter data with case insensetive term

一笑奈何 提交于 2019-12-10 13:15:02

问题


This is how I filter some data by title value:

data.filter(x => x.title.includes(term))

So data like

Sample one
Sample Two
Bla two

will be 'reduced' to

Bla two

if I'm filtering by two.

But I need to get the filtered result

Sample Two
Bla two

回答1:


You can use a case-insensitive regular expression:

// Note that this assumes that you are certain that `term` contains
// no characters that are treated as special characters by a RegExp.
data.filter(x => new RegExp(term, 'i').test(x.title));

A perhaps easier and safer approach is to convert the strings to lowercase and compare:

data.filter(x => x.title.toLowerCase().includes(term.toLowerCase()))


来源:https://stackoverflow.com/questions/44469548/es6-filter-data-with-case-insensetive-term

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!