Split camel case string with space using angularjs filter
Asked Answered
P

2

6

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>
Pearson answered 20/2, 2018 at 15:25 Comment(0)
G
14

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>
Gerbold answered 20/2, 2018 at 15:31 Comment(2)
I need an absolute question? You didnt specify exactly what you want the output to be. So I gave you a generic answer.Gerbold
If string is like "RegisterEmail" and I want to show it like "Register Email" mean split them with spacePearson
S
11

If you're using Angular 2 +, you can create a custom pipe:

Create humanize.ts:

import {Pipe} from ‘angular2/core’;

@Pipe({
name: ‘humanize’
})

 export class HumanizePipe {
 transform(value: string) {
 if ((typeof value) !== ‘string’) {
 return value;
 }
 value = value.split(/(?=[A-Z])/).join(‘ ‘);
 value = value[0].toUpperCase() + value.slice(1);
 return value;
 }
}

Add an entry in app.module.ts -> declarations

@NgModule({
  declarations: [
  AppComponent,
   HumanizePipe,
...

Use it like this

<label>{{CamelCase | humanize}}</label>

It will display "Camel Case"

Adapted from here

Satrap answered 9/5, 2019 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.