Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 564
habib Avatar asked Feb 20 '18 15:02

habib


2 Answers

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>
like image 51
Pezetter Avatar answered Nov 15 '22 07:11

Pezetter


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

like image 21
The One Avatar answered Nov 15 '22 08:11

The One