AngularJS Capitalize Filter

Over a month ago I was messing around with CSS when I realized the text-transform property with the capitalize keyword works just with lowercase text, as it forces the first letter of each word to be converted to uppercase keeping the rest of the characters unchanged.

In the current project I’m working on I’m getting uppercased text from the Rest API so this was the perfect scenario to create my first AngularJS filter. Moreover, as we are working with team names, we need a special letter case where team abbreviations are displayed like CD Logroñés or FC Barcelona.

It was really simple for me to create this filter and I decided to open source it as it might be helpful for somebody else who needs capitalization or just as a base for developing a custom filter.

angular.module('angular-capitalize-filter', [])
  .filter('capitalize', function() {
    return function (input, format) {
      if (!input) {
        return input;
      format = format || 'all';
      if (format === 'first') {
        // Capitalize the first letter of a sentence
        return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
      } else {
        var words = input.split(' ');
        var result = [];
        words.forEach(function(word) {
          if (word.length === 2 && format === 'team') {
            // Uppercase team abbreviations like FC, CD, SD
          } else {
            result.push(word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
        return result.join(' ');

For now it has just three options: capitalize all the words in a sentence, capitalizes just the first word of a sentence and the special one for team names.

You can feel free to install it using Bower or fork it from the repository.

> bower install angular-capitalize-filter

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s