Skip to content

Instantly share code, notes, and snippets.

@marufsiddiqui
Created May 22, 2013 07:34
Show Gist options
  • Save marufsiddiqui/5625869 to your computer and use it in GitHub Desktop.
Save marufsiddiqui/5625869 to your computer and use it in GitHub Desktop.
A Sample AngularJS filter
var homeModule = angular.module('HomeModule', []);
homeModule.filter('titleCase', function () {
return function (input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
}
return words.join(' ');
}
});
@anton000
Copy link

@Autodidaktosaur doesnt seem to work on All caps

@benhoIIand
Copy link

Nice simple filter that works with all caps:

angular.module('app.filters')
    .filter('titleCase', function() {
        return function(str) {
            return (str == undefined || str === null) ? '' : str.replace(/_|-/, ' ').replace(/\w\S*/g, function(txt){
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        }
    });

Tests to go with it if you want them:

describe('titleCase', function() {

    var fixtures = [
        'AWAITING DISPATCH',
        'AWAITING_DISPATCH',
        'AWaiTing-DISPatcH',
        'Awaiting DISPATCH'
    ];

    beforeEach(module('app.filters'));

    it('should convert strings correctly', inject(function(titleCaseFilter) {

        fixtures.forEach(function(fixture) {
            expect(titleCaseFilter(fixture)).toEqual('Awaiting Dispatch');
        });

    }));

    it('should return an empty string when a value is not passed', inject(function(titleCaseFilter) {
        expect(titleCaseFilter()).toEqual('');
        expect(titleCaseFilter(null)).toEqual('');
    }));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment