Search code examples
angularjsregexangularjs-filter

create an angular regex filter


I am trying to create an Angular filter to provide regex functionality. I am consuming the flickr API - see example here and one key value of the json object returned is

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

Currently, this is my filter regex function:

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

and in my html I have this

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

and the filter is injected into the controller, which looks like this

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

I am looking to isolate just the user's name and drop the [email protected] so that John Doe is returned

Any guidance on how to implement this would be greatly appreciated.

Thanks!


Solution

  • You could try adding a filter like this

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

    Working JSFiddle here http://jsfiddle.net/WfuAh/147/