创建一个角度正则表达式过滤器

问题描述 投票:1回答:1

我正在尝试创建一个Angular过滤器来提供正则表达式功能。我正在使用flickr API - see example here和返回的json对象的一个​​键值

{......
   "author": "[email protected] (John Doe)"
....}

目前,这是我的过滤器正则表达式功能:

app.filter('regex', function() {
    return function(input, regex) {
        return input.match(regex);  
    }
})

在我的HTML中,我有这个

<p>{{user.author | regex:'(/\((.*?))\)/g)'}}</p>

并将过滤器注入控制器,如下所示

app.controller('testCtrl', function ($http, regexFilter) {
      //do controller stuff!
}

我希望只隔离用户的名字并删除[email protected]以便返回John Doe

任何关于如何实现这一点的指导将不胜感激。

谢谢!

angularjs regex angularjs-filter
1个回答
5
投票

您可以尝试添加这样的过滤器

var myApp = angular.module('myApp', []);
myApp.filter('regex', function() {
   return function(val){
     var RegExp = /\(([^)]+)\)/;
     var match = RegExp.exec(val);
     return match[1];
   };
});
myApp.controller('ctrl', function($scope){
    $scope.user = {'author': "[email protected] (John Doe)"};
});

在这里工作JSFiddle http://jsfiddle.net/WfuAh/147/

© www.soinside.com 2019 - 2024. All rights reserved.