逐字符过滤字符串列表的最有效方法是什么?
var term = "Mike";
angular.forEach($scope.contacts, function(contact, key) {
// if I had the whole term and
// contact.name == Mike then this is true
contact.name == term;
});
上面的内容没问题,但如果我要构建搜索,我该如何逐个字符地过滤?
var term = "Mi";
angular.forEach($scope.contacts, function(contact, key) {
// contact.name == Mike, but term == Mi how can I get this to return true?
contact.name == term;
});
最佳答案
使用indexOf
var term = "Mi";
angular.forEach($scope.contacts, function(contact, key) {
// contact.name == Mike, but term == Mi how can I get this to return true?
contact.name.indexOf(term) > -1;
});
如果你想要不区分大小写的测试,你可以这样做
var term = "Mi";
var regex = new RegExp(term, 'i');
angular.forEach($scope.contacts, function(contact, key) {
// contact.name == Mike, but term == Mi how can I get this to return true?
regex.test(contact.name);
});
关于Javascript 通过匹配输入来过滤字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793371/