Created
May 22, 2013 07:34
-
-
Save marufsiddiqui/5625869 to your computer and use it in GitHub Desktop.
A Sample AngularJS filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(' '); | |
} | |
}); |
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
@Autodidaktosaur doesnt seem to work on All caps