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

标签 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

非常感谢。

最佳答案

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

您也可以从正则表达式中删除括号。

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

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

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

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

关于javascript - 如何将 string match() 与 angularJs $scope.search 变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27780976/

相关文章:

javascript - 尝试创建 jquery mouseover 和 mouseout 事件

javascript - JavaScript 中的异步数据检索

regex - 如何从 Dart 中的字符串中仅删除符号

javascript - Angular1.3 : Access controller function inside recursive directive template?

javascript - AngularJS Protractor : randomly fail in headless mode (Firefox)

javascript - jquery 表单结果未显示。我的代码错了吗?

javascript - 内联样式 react 组件的可变样式对象

Java表达式: Not allow single quote in middle or Allow single quote with double back slash

php - 使用 PHP 从字符串中获取数字

javascript - 如何在 angularjs 中的两个单独的 Controller 中运行函数