Capitalization of First Letter in Angular with a Custom Filter (And JavaScript generally too).

Capitalization of First Letter in Angular with a Custom Filter (And JavaScript generally too).

Capital not Capitol.

Angular has some great built in filters, but one case that comes up the Angular doesn’t handle automatically capitalizing the first letter in a string. (Skip to the bottom to get the code snippet if you don’t care about my babbling)

For capitalizing the first letter, but leaving the rest of the string the same, we’ll use the substring, toLowerCase and toUpperCase methods.

I’m assuming you have a module set up, I’m using the app convention.

The regular JavaScript for capitalizing goes like this:

JavaScript

1

2

3

4

5

6

7

8

9

varourString="string";

allUpper=ourString.toUpperCase();// This will make a whole string uppercase, result: STRING

allLower=ourString.toLowerCase();// The whole string will be lower case, result: STRING

//This will make the first letter uppercase, leaving the rest of the string alone. This will yield "String" in this situation, but if you had the the value "strinG" this would result in "StrinG." This might not be what you wanted, so it should not be used if your looking to display the string with only capitalization.

Notice the substring method treats the string as an array, the first argument in the substring is the index (or start position) and starts counting at zero. The second argument in substring is optional, and tells how many letters/characters you want to count through and send forward into the next method or return.

Notice the filter method on app (our module), the first argument is the name and the second is the function. Within, we’re returning another function which takes the input (the value from the template) with the capitalized first letter. Also note, I’ve added in a conditional, dependent on input being defined. That way if there’s no value there it won’t produce an error. In the template we’d include something like this {{ value | firstUpper }}