如何将string match()与angularJs $ scope.search变量一起使用

时间:2015-01-05 13:52:46

标签: javascript regex angularjs match

我尝试将字符串匹配与忽略区分大小写和我的输入$scope.search变量一起使用,但它不起作用。

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

});

数据对象组:

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

如何正确使用 group.lable.match()$scope.search

非常感谢。

2 个答案:

答案 0 :(得分:1)

您的正则表达式是动态的,因此您无法使用/regexp/语法。您需要创建一个Regexp对象。

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

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

您也可以从RegExp中删除括号。

最好使用test(),因为您对结果不感兴趣:

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

最后,如果这是一个基本搜索,将两个部分放在小写并使用indexOf应该更有效:

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

答案 1 :(得分:0)

你总是可以在angularjs模块中使用javascript:)

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

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

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

});

这应该可以解决您的问题