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

标签 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;

});

最佳答案

使用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/

相关文章:

regex - 如何仅从此字符串获取链接?

regex - 什么正则表达式将匹配模式或为空?

javascript - 如何在 Jasmine 中比较两个具有浮点值的对象?

javascript - 我想在我的导航中添加一些类(class)

javascript - 使用 jQuery 同时使用文本框和复选框过滤数据?

php 理解贪婪与非贪婪匹配

c# - http重定向问题

javascript - 如何使用angular $http发送FormData

ruby-on-rails - 名称的正则表达式

java - 正则表达式处理键值对