Capitalize the first letter of string in AngularJs

Piyush picture Piyush · May 13, 2015 · Viewed 168.6k times · Source

I want capitalize first character of string in angularjs

As i used {{ uppercase_expression | uppercase}} it convert whole string to upper case.

Answer

Nidhish Krishnan picture Nidhish Krishnan · May 13, 2015

use this capitalize filter

var app = angular.module('app', []);

app.controller('Ctrl', function ($scope) {
   $scope.msg = 'hello, world.';
});

app.filter('capitalize', function() {
    return function(input) {
      return (angular.isString(input) && input.length > 0) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : input;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <p><b>My Text:</b> {{msg | capitalize}}</p>
    </div>
</div>