Javascript 通过匹配输入来过滤字符串

Javascript filter strings by matching input?

本文关键字:过滤 字符串 输入 Javascript      更新时间:2023-09-26

逐个字符过滤字符串列表的最有效方法是什么?

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);
    });