April 3, 2015

Build a filter that capitalizes each word in a string with AngularJS

AngularJS filter that converts uppercase strings with multiple words to lowercase strings, with capitalized words. Works as vanilla JavaScript too!

The post was written by Dan Mindru, the maker of Shipixen—the best Next.js boilerplate.

Build a filter that capitalizes each word in a string with AngularJS

By working with AngularJS we are bound to create all sorts of filters and directives on a daily basis. I was thinking it’s a good idea to share some of mine every now and then. Perhaps they will save somebody time or give her/him an idea of how to solve a problem.

I created the capitalize filter for a the following use case: I had to convert uppercase strings with multiple words to lowercase strings, with capitalized words: MOUNTAIN DOOM -> Mountain Doom

CSS won’t do the trick here, so JavaScript to the rescue! The code is for an AngularJS filter, but it would work just as well if you strip out the .filter() wrapper and use it as plain JavaScript.

Grab it from github, see a quick demo here or add it as a dependency to your app using bower install ng-capitalize --save.

myModule.filter("capitalize", function () {
    return function (input) {
        if (input.indexOf(" ") !== -1) {
            var inputPieces, i;

            input = input.toLowerCase();
            inputPieces = input.split(" ");

            for (i = 0; i < inputPieces.length; i++) {
                inputPieces[i] = capitalizeString(inputPieces[i]);
            }

            return inputPieces.toString().replace(/,/g, " ");
        } else {
            input = input.toLowerCase();
            return capitalizeString(input);
        }

        function capitalizeString(inputString) {
            return (
                inputString.substring(0, 1).toUpperCase() +
                inputString.substring(1)
            );
        }
    };
});

See it in action here.

I assume somebody else had to code a similar piece at some point, but I just couldn’t find it with my searches. So there it is, hope you found it easy!


If you liked the post, you might like Shipixen—a Next.js boilerplate that allows you to ship a beautifully designed Blog, Landing Page, SaaS, Waitlist or anything in between. Today!