Beginning AngularJS

(WallPaper) #1
Chapter 4 ■ Filters and Modules

console.log(toTitleCase("jennifer"));
console.log(toTitleCase("jENniFEr"));
console.log(toTitleCase("jENniFEr amanda Grant"));



Let’s have a look at the output of Listing 4-14 and see if it meets our needs.

Jennifer
Jennifer
Jenni.amanda grant


It’s a fairly simple function, and it does what we need it to do. That is to say, it will indeed convert the firstName and
surname to title case. It does so by using the string method’s charAt() method to access and convert the first character
to uppercase (as returned by str.charAt(0).toUpperCase()) and concatenating the resulting value to a lowercased
portion of the string that consists of all but the first character (as returned by str.substr(1).toLowerCase()).
However, I don’t like the fact that this function works only on the very first word when it is given a multiple word
string as an argument. While we could perhaps get away with this for the cases in which we only want to work with a
single word, it is not a very forward-thinking approach. Let’s add the ability to handle multiple words (see Listing 4-15).


Listing 4-15. A Better Title Casing Function



The following output shows that this is a better implementation. The last line now shows that each word has had
its first character converted to uppercase.


Jennifer
Jennifer
Jennifer Amanda Grant

Free download pdf