Search code examples
javascriptangularjsregexangular-filters

How do I get a number to render in my UI with a space after every 4 characters?


I have a 16 digit property that comes back for example(1234123412341234). I would like it to render on my UI with a space every 4 number characters for example(1234 1234 1234 1234). I'm using Angular JS so I'm looking for a way to accomplish this. I'm pretty sure it's either a custom Angular filter or regex related, but my knowledge of either and how to implement it is limited.


Solution

  • AngularJS filter is easy to setup. Just accept one parameter and apply any JS formatting on it. Here is a working example:

    var app = angular.module('myApp', []);
    app.filter('myFilter', function() {
      return function(x) {
        return x.toString().replace(/\d{4}(?=.)/g, '$& '); // your format filter here
      };
    });
    app.controller('demoCtrl', function($scope) {
      $scope.test = 1234123412341234;
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
      <div ng-app="myApp" ng-controller="demoCtrl">
        {{test | myFilter}}
      </div>
    </body>
    </html>

    (I took regex code from Nina Scholz's answer. Feel free to use any other regex)