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

时间:2016-01-14 15:30:35

标签: javascript regex

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

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;

});

1 个答案:

答案 0 :(得分:5)

使用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);

    });