javascript - How to use string match() with angularJs $scope.search variable - Stack Overflow

I try to use string match with ignore case sensitivity and my input $scope.search variable, but it does

I try to use string match with ignore case sensitivity and my input $scope.search variable, but it doesn't work.

<input type="text" ng-model="search" autofocus="autofocus">




angular.forEach(groups, function(group, key) {

   console.log(group); // => Object contains

    if (group.label.match(/($scope.search)/i)) {
      result[key] = group;
    }

});

Data Object group:

Object { label: "Transfiguration", articles: Array[1] }

How to use group.lable.match() with $scope.search correctly?

Many thanks.

I try to use string match with ignore case sensitivity and my input $scope.search variable, but it doesn't work.

<input type="text" ng-model="search" autofocus="autofocus">




angular.forEach(groups, function(group, key) {

   console.log(group); // => Object contains

    if (group.label.match(/($scope.search)/i)) {
      result[key] = group;
    }

});

Data Object group:

Object { label: "Transfiguration", articles: Array[1] }

How to use group.lable.match() with $scope.search correctly?

Many thanks.

Share Improve this question edited Jan 5, 2015 at 14:05 asked Jan 5, 2015 at 13:52 user4420255user4420255
Add a ment  | 

2 Answers 2

Reset to default 1

Your regular expression is dynamic so you cannot use /regexp/ syntax. You need to create a Regexp object instead.

angular.forEach(groups, function(group, key) {
    console.log(group); // => Object contains

    if (group.label.match(new RegExp("(" + $scope.search + ")", "i"))) {
      result[key] = group;
    }
});

You can probably remove the brackets from the RegExp too.

It is better also to use test() because you aren't interested in the results:

if(new RegExp($scope.search, "i").test(group.label)) {

Finally, if this is a basic search, putting both parts to lower case and using indexOf should be more efficient:

if (group.label.toLowerCase().indexOf($scope.search.toLowerCase()) > -1) {

you can always use javascript in angularjs modules :)

angular.forEach(groups, function(group, key) {

   console.log(group); // => Object contains

    if (group.label.toLowerCase().indexOf($scope.search.toLowerCase())!=-1) {
      result[key] = group;
    }

});

This should solve your problem

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745614687a4636160.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信