Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13422

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;

});

Upvotes: 3

Views: 69

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

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

    });

Upvotes: 5

Related Questions