Javascript通过匹配输入过滤字符串?
按字符过滤字符串列表的最有效方法是什么Javascript通过匹配输入过滤字符串?,javascript,regex,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($scop
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;
});
上面的内容很好,但是如果我正在构建搜索,如何逐个字符进行过滤
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);
});
您确实必须定义部分匹配的含义,因此对于您的最后一个示例,“Tommie”是有效匹配吗?根据您提出的规则,有许多不同的方法可以做到这一点。您不区分大小写的解决方案使用正则表达式,这可以更改正则表达式语言中具有特殊含义的字符的
术语的含义。相反,考虑将两个值转换为同一种情况(即:代码> TooWraseCase](< /代码>),并执行<代码>索引> <代码>。伟大的建议Helcon,现在肯定会这样做:“Halcon,我不确定你的意思是<代码>。这可以改变术语< /Cord>的含义。你的意思是语言上的,还是会有程序上的意外副作用?如果term
是Mi*
你会匹配Mi
,miii
但也m
@Halcyon,对不起,还是不理解:-)。在控制台newregexp('Mi','i')中执行此操作。test('m')
将为我提供false