最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - filters with wildcards in angularjs - Stack Overflow

programmeradmin4浏览0评论

I'm trying to filter a list of values with wildcards.

searchString = "ab*cd"

Should return all the values that start with "ab" and end with "cd".

So far I've tried to split the string in multiple substrings where the asterisk is and then search all the word that starts with the first substring and simultaneously end with the second one (or one of the two, depending on the position of the asterisk).

I'm asking if there is a better method of doing this.

This is the code to search strings that start with a searchString:

function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}

$scope.query = '';
var regex;
$scope.$watch('query', function (value) {
regex = new RegExp('\\b' + escapeRegExp(value), 'i');
}

$scope.filterBySearch = function(article) {
if (!$scope.query) return true;
return regex.test(article.title);
};

I'm trying to filter a list of values with wildcards.

searchString = "ab*cd"

Should return all the values that start with "ab" and end with "cd".

So far I've tried to split the string in multiple substrings where the asterisk is and then search all the word that starts with the first substring and simultaneously end with the second one (or one of the two, depending on the position of the asterisk).

I'm asking if there is a better method of doing this.

This is the code to search strings that start with a searchString:

function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}

$scope.query = '';
var regex;
$scope.$watch('query', function (value) {
regex = new RegExp('\\b' + escapeRegExp(value), 'i');
}

$scope.filterBySearch = function(article) {
if (!$scope.query) return true;
return regex.test(article.title);
};
Share Improve this question edited Aug 18, 2014 at 10:44 Sortee asked Aug 18, 2014 at 10:24 SorteeSortee 631 silver badge6 bronze badges 1
  • 1 Check this answer. – bmleite Commented Aug 18, 2014 at 10:36
Add a ment  | 

1 Answer 1

Reset to default 5

Write custom filter like:

iApp.filter('myfilter', function() {
   return function( items, types) {
    var filtered = [];

    angular.forEach(items, function(item) {
       if(types.wildcard == false || item.name.match(types.value)) {
          filtered.push(item);
        }

    });

    return filtered;
  };
});

where filter should be:

$scope.types = {wildcard:false, value: /^ab.*cd$/};

HTML example

  <tr data-ng-repeat="value in values |  myfilter:types">

Demo Plunker

发布评论

评论列表(0)

  1. 暂无评论