Kaizar Laxmidhar
Kaizar Laxmidhar

Reputation: 869

Format input data with regex in AngularJS

I have some data in the following format. With the use of regex I want to display only the first two tokens.

For example AB.JKL.MNO.XYZ => AB.JKL

AB.JKL.MNO.XYZ
KJ.KJLJ.KD.IUOI
KLJ.LK.LJ.JL.OLJ.JLL

Note: I am using AngularJS I can achieve this using Angularjs expression directly in the html but the html is a common template where other data is also being displayed I don't want to corrupt it. Therefore I want to apply regex on data in controller.

Upvotes: 1

Views: 1490

Answers (1)

lcoderre
lcoderre

Reputation: 1303

Regex-wise:

If you want to grab a <letters><dot><letters> format, this regex will capture at the beginning: ^([^.]+\.[^.]+)

Same thing, but at the end of your string: ([^.]+\.[^.]+)$

Angular-wise

I am not so familiar with angular, but from what I understand, you can create your own type of filters.

<div ng-app='myApp' ng-controller="Main">
    first token: {{name | firstToken}} </br>
    last token: {{name | lastToken}}</br>
    any Regex: {{name | regex:"[^.]+$"}}</br>
</div>
var myApp = angular.module('myApp', []);
myApp.filter('regex', function () {
    return function (input, regex) {
        if (!input) return '';
        var matches = input.match(regex);
        if (matches) return matches[0];
        return "";
    };
}).filter('firstToken', function () {
    return function (input) {
        if (!input) return '';
        var matches = input.match(/([^.]+.[^.]+)/);
        if (matches) return matches[0];
        return "";
    };
});

function Main($scope) {
    $scope.name = 'AB.JKL.MNO.XYZ';
}

Have fun, play with it: http://jsfiddle.net/lcoderre/WfuAh/97/

Upvotes: 2

Related Questions