javascript 如何将字符串 match() 与 angularJs $scope.search 变量一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27780976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:59:04  来源:igfitidea点击:

How to use string match() with angularJs $scope.search variable

javascriptregexangularjsmatch

提问by Khaleel

I try to use string match with ignore case sensitivityand my input $scope.searchvariable, but it doesn't work.

我尝试使用忽略大小写敏感度和我的输入$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;
    }

});

Data Object group:

数据对象组:

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

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

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

Many thanks.

非常感谢。

回答by Rhumborl

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

您的正则表达式是动态的,因此您不能使用/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;
    }
});

You can probably remove the brackets from the RegExp too.

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

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

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

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

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

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

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

回答by Khaleel

you can always use javascript in angularjs modules :)

你总是可以在 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;
    }

});

This should solve your problem

这应该可以解决您的问题