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;
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With