Search code examples
angularjsfilterangularjs-filter

Split camel case string with space using angularjs filter


I want to split camel case string to regular form and want to use customize filter.

<select class="form-control" ng-model="emailsettingType" ng-change="emailsettingTypeChange()" name="emailsettingType" ng-required="true">
<option ng-repeat="opt in emailtypesforuser">{{opt|splitCamelCase}}</option>
</select>

Solution

  • This can be customized to fit your needs.

    .filter('splitCamelCase', [function () {
      return function (input) {
    
        if (typeof input !== "string") {
          return input;
        }
    
        return input.split(/(?=[A-Z])/).join(' ');
    
      };
    }]);
    

    Remove the toUpperCase() if you do not want every first character capitalized.

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.emailtypesforuser = ['OneType', 'AnotherType', 'thisType', 'thatType', 'THatTypppeRRR'];
    });
    
    app.filter('splitCamelCase', [function () {
      return function (input) {
    
        if (typeof input !== "string") {
          return input;
        }
    
        return input
         .replace(/([A-Z])/g, (match) => ` ${match}`)
         .replace(/^./, (match) => match.toUpperCase());
    
      };
    }]);
    <!DOCTYPE html>
    <html ng-app="plunker">
    
      <head>
        <meta charset="utf-8" />
        <title>AngularJS Plunker</title>
        <script>document.write('<base href="' + document.location + '" />');</script>
        <link href="style.css" rel="stylesheet" />
        <script src="https://code.angularjs.org/1.5.4/angular.js"></script>
        <!-- By setting the version to snapshot (available for all modules), you can test with the latest master version -->
        <!--<script src="https://code.angularjs.org/snapshot/angular.js"></script>-->
        <script src="app.js"></script>
      </head>
    
      <body ng-controller="MainCtrl">
        <p ng-repeat="opt in emailtypesforuser">{{opt|splitCamelCase}}</p>
      </body>
    </html>