Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript filter strings by matching input?

What is the most efficient way to filter a list of strings character by character?

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;

});

The above would be fine, but if I am building a search how can I filter character by character?

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;

});
like image 841
Michael Joseph Aubry Avatar asked Feb 08 '26 00:02

Michael Joseph Aubry


1 Answers

Use 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;

});

If you want case insensitive testing, you can do

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

    });
like image 136
AmmarCSE Avatar answered Feb 12 '26 06:02

AmmarCSE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!